软件开发过程中使用Java反射机制时遇到了下面的问题
com.ruoyi.web.controller.test.bean.HeadTeacher@4b9af9a9
com.ruoyi.web.controller.test.bean.HeadTeacher@4b9af9a9
java.lang.NoSuchMethodException: com.ruoyi.web.controller.test.bean.HeadTeacher.<init>(java.lang.String, int)
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.getConstructor(Class.java:1825)
at com.ruoyi.web.controller.test.ReflectionDemo.getInstance(ReflectionDemo.java:49)
at com.ruoyi.web.controller.test.ReflectionDemo.main(ReflectionDemo.java:69)
代码如下:
package com.ruoyi.web.controller.test;
import com.ruoyi.web.controller.test.bean.HeadTeacher;
import com.ruoyi.web.controller.test.bean.Student;
public class ReflectionDemo {
/**
* @param className
* @param params 代表参数的值
* @param paramsType 代表构造器参数的类型
* @return
*/
public Object getInstance(String className, Object[] params, Class[] paramsType) {
Object obj = null;
Class clazz = null;
try {
//获取className字符串所代表的类的Class实例
clazz = Class.forName(className);
//使用clazz获取className所代表的类的构造器,然后使用newInstance方法获取这个类的实例
obj = clazz.getConstructor(paramsType).newInstance(params);
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
public static void main(String[] args) {
ReflectionDemo demo = new ReflectionDemo();
/**
* 测试带参数的方法
*/
Object obj = demo.getInstance("com.ruoyi.web.controller.test.bean.HeadTeacher"
,new Object[]{"王校长",50},new Class[]{String.class,Integer.TYPE});
HeadTeacher ht = new HeadTeacher();
System.out.println(ht);
ht.setHtName("王本山");
ht.setHtAge(48);
System.out.println(ht);
}
}
JavaBean对象代码:
package com.ruoyi.web.controller.test.bean;
public class HeadTeacher {
private String htName;
private int htAge;
public String getHtName() {
return htName;
}
public void setHtName(String htName) {
this.htName = htName;
}
public int getHtAge() {
return htAge;
}
public void setHtAge(int htAge) {
this.htAge = htAge;
}
public void sayHello() {
System.out.println(this.htName + "\t" + this.htAge);
}
}
反复分析给出的错误提示,发现实例化HeadTeacher对象时,该类中并不存在带参构造器,因此
bean对象中添加如下代码
public HeadTeacher(String name,int age){
this.htName= name;
this.htAge = age;
}
再次运行结果如下: