這是個測試用的例子,通過反射調用對象的方法。 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) {
this.msg = msg;
}
public String getMsg() {
return msg;
}
public void outInfo() {
System.out.println( "這是測試Java反射的測試類別");
}
} 控制台輸出結果: 這是測試Java反射的測試類別
重新設定msg資訊。
Process finished with exit code 0
傳送門:http://blog.csdn.net/hbcui1984/article/details/2719089
JAVA反射使用手記
本篇文章為在工作中使用JAVA反射的經驗總結,也可以說是一些小技巧,以後學會新的小技巧,會不斷更新。本文不準備討論JAVA反射的機制,網上有很多,大家隨便google一下就可以了。
在開始之前,我先定義一個測試類別Student,代碼如下: [Java] view plain copy package chb.test.reflect; public class Student { private int age; private String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static void hi(int age,String name){ System.out.println("大家好,我叫"+name+",今年"+age+"歲"); } }<pre></pre>
一、JAVA反射的常規使用步驟
反射調用一般分為3個步驟: 得到要調用類的class 得到要調用的類中的方法(Method) 方法調用(invoke)
程式碼範例: [Csharp] view plain copy Class cls = Class.forName("chb.test.reflect.Student"); Method m = cls.getDeclaredMethod("hi",new Class[]{int.class,String.class}); m.invoke(cls.newInstance(),20,"chb");<pre></pre>
二、方法調用中的參數類型
在方法調用中,參數類型必須正確,這裡需要注意的是不能使用封裝類替換基本類型,比如不能使用Integer.class代替int.class。
如我要調用Student的setAge方法,下面的調用是正確的:
[Java] view plain copy Class cls = Class.forName("chb.test.reflect.Student"); Method setMethod = cls.getDeclaredMethod("setAge",int.class); setMethod.invoke(cls.newInstance(), 15);<pre></pre>
而如果我們用Integer.class替代int.class就會出錯,如: [Java] view plain copy Class cls = Class.forName("chb.test.reflect.Student"); Method setMethod = cls.getDeclaredMethod("setAge"