通過Java反射調用方法
這是個測試用的例子,通過反射調用對象的方法。
TestRef.java
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
/**
* Created by IntelliJ IDEA.
* File: TestRef.java
* User: leizhimin
* Date: 2008-1-28 14:48:44
*/
public class TestRef {
public static void main(String args[]) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Foo foo = new Foo("這個一個Foo對象!");
Class clazz = foo.getClass();
Method m1 = clazz.getDeclaredMethod("outInfo");
Method m2 = clazz.getDeclaredMethod("setMsg", String.class);
Method m3 = clazz.getDeclaredMethod("getMsg");
m1.invoke(foo);
m2.invoke(foo, "重新設定msg資訊!");
String msg = (String) m3.invoke(foo);
System.out.println(msg);
}
}
class Foo {
private String msg;
public Foo(String msg) {
this.msg = msg;
public void setMsg(String msg) {
public String getMsg() {
return msg;
public void outInfo() {
System.out.println("這是測試Java反射的測試類");
控制台輸出結果:
這是測試Java反射的測試類
重新設定msg資訊!
Process finished with exit code 0
推薦JAVA教育訓練機構,黑馬程式員 AND 傳智播客 有條件的朋友可以前去報名學習。
如果沒有條件的朋友,建議直接購買低價的2017傳智播客JAVAEE課堂上的視訊教程
視訊傳送門 連結:2017最新整理傳智播客JavaEE第49期 基礎就業班