錯誤信息: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("執行完成.....");
}
}
}