錯誤信息:object is not an instance of declaring class
說明Class沒有實例化;
解決辦法:
由於沒有實力化可以有如下兩種方法:
1、反射方法定義成為static的,故被反射類就不需要實例化;
2、method.invoke(class.newInstance(), args);
舉栗子:對應第一種方法
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("執行完成.....");
}
}
}
舉栗子:對應第二種方法
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("執行完成.....");
}
}
}