2008年4月21日 Edited By DingDangXiaoMa
Java 類反射,方法反射
/**
* 測試類反射,方法反射反射的例子。
* @author DingDangXiaoMa
*/
public class TestMethod {
/**
* 不帶參數的方法。被調用的方法。
*/
public void test1() {
System.out.println("in the method 1
");
}
/**
* 主調方法。由test2方法調用test1(),
*/
public void test2() {
try {
Method method = getClass().getMethod("test1");
method.invoke(this, new Object[]{});
} catch (Exception ex) {
System.out.println("無法找到方法。");
}
}
/**
*帶參數的被調方法。 test1
* 打印出傳遞過來的參數。
* @param ss
*/
public void test1(String ss) {
System.out.println(ss);
}
/**
* 調用帶參數的方法test1(String ss);
* 參數為String 類型
*/
public void t() {
try {
Method method = getClass().getMethod("test1", new Class[]{
java.lang.String.class
});
method.invoke(this, new Object[]{
"aa"
});
} catch (Exception _ex) {
// printwriter.println("Method not supported");
System.out.println("沒有找到方法。");
}
}
public static void main(String[] args) {
TestMethod test = new TestMethod();
test.t(); //調用帶參數的方法。
test.test2(); //調用不帶參數的方法。
}