object is not an instance of declaring class

错误信息:object is not an instance of declaring classjava

说明Class没有实例化;
解决办法:
因为没有实力化能够有以下两种方法:
一、反射方法定义成为static的,故被反射类就不须要实例化;
二、method.invoke(class.newInstance(), args); spa

 

举栗子:对应第一种方法get

public static void testSys(String msgs) {
System.out.println("java 反射机制调用方法执行,msg:" + msgs);
}

@Test
public void test(){
System.out.println("-------------获取当前类-----------------------");
String msg = "hello";
Class<? extends Test> aClass1 = getClass();
Method[] methods = aClass1.getMethods();
for (Method method : methods) {
if (method.getName().equals("testSys")) {
System.out.println("匹配成功,开始执行反射方法,methodName:" + method.getName());
System.out.println("aClass1:" + aClass1);
System.out.println("aClass1Name:" + aClass1.getName());
method.invoke(aClass1, msg);
System.out.println("执行完成.....");
}
}
}

举栗子:对应第二种方法class

public void testSys(String msgs) {
System.out.println("java 反射机制调用方法执行,msg:" + msgs);
}

@Test
public void test(){
System.out.println("-------------获取当前类-----------------------");
String msg = "hello";
Class<? extends Test> aClass1 = getClass();
Method[] methods = aClass1.getMethods();
for (Method method : methods) {
if (method.getName().equals("testSys")) {
System.out.println("匹配成功,开始执行反射方法,methodName:" + method.getName());
System.out.println("aClass1:" + aClass1);
System.out.println("aClass1Name:" + aClass1.getName());
method.invoke(aClass1.newInstance(), msg);
System.out.println("执行完成.....");
}
}
}
相关文章
相关标签/搜索