一般获得Class类的实例时候,如果类构造方法有参数的话要传入参数列表,但是我下面的方式就一直提示找不到方法:
package com.liuyi.Reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class ReflectionTest2 {
public static void main(String[] args) throws Exception {
Class classType = Demo.class;
// Object obj=classType.newInstance();
Constructor<?> cons = classType.getConstructor(new Class[]{String.class,int.class});
Object obj = cons.newInstance(new Object[]{"zhangsan",21});
Method method = classType.getMethod("add", new Class[] { int.class,
int.class });
Object obj2 = method.invoke(obj, new Object[] { 1, 2 });
System.out.println(obj2);
}
}
class Demo {
private String name;
private int age;
// Demo() {
// }
public Demo(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int add(int a, int b) {
return a + b;
}
}
报的错误是 java.lang.NoSuchMethodException: com.liuyi.Reflection.Demo.<init>
请帮忙看看问题出在那里了?
|
|