開發(fā)的時候有時候會碰到這樣的情況,我們在寫程序的時候并不知道需要調(diào)用某個對象的哪個方法,只有程序運行后,我們才能夠知道?;蛟S我們需要根據(jù)客戶端傳過來的某個String參數(shù)的值來判斷我們應(yīng)該執(zhí)行哪個方法。在這種情況下JAVA的反射執(zhí)行就可以幫上忙了。下面是考試大做的一個簡單的測試代碼,提供給大家做個參考。
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/** *//**
* 測試JAVA reflect機制
*/
public class TestRef{
/** *//**
* @param args
*/
public static void main(String[] args){
TestBean test = new TestBean();
Method[] methods = test.getClass().getMethods();
test.setAbc("---");
for(int i=0;i
if(methods[i].getName().equalsIgnoreCase("getabc")){
try {
System.out.println(methods[i].invoke(test));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/** *//**
* 測試JAVA reflect機制
*/
public class TestRef{
/** *//**
* @param args
*/
public static void main(String[] args){
TestBean test = new TestBean();
Method[] methods = test.getClass().getMethods();
test.setAbc("---");
for(int i=0;i
if(methods[i].getName().equalsIgnoreCase("getabc")){
try {
System.out.println(methods[i].invoke(test));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}

