反射思想由來已久,由於一直對java中反射的用法一直不太熟悉,特地找了一些資料學習了 一下,現在通過以下一些執行個體,對java中反射機制的一些用法做一些介紹:
獲得執行個體對象的一個field,method,constructor
下面是一個簡單的例子:
package reflection;
import java.lang.reflect.Field;
public class GetFieldSimple {
public int height;
private int width;
public GetFieldSimple(int height, int width) {
super();
this.height = height;
this.width = width;
}
static void printHeight(GetFieldSimple gfs){
Field heigthField;
Method method;
Constructor cons;
Integer height;
Class c =gfs.getClass(); //獲得運行時對象
//省略了try catch的代碼
heigthField=c.getField("height"); //獲得指定的欄位封裝為對象
height = heigthField.getInt(gfs); //從對象中取出欄位值
System.out.println(height);
heigthField=c.getDeclaredField("width");//width是private型
height = heigthField.getInt(gfs);
System.out.println(height);
method=c.getMethod("printMethodName1");
System.out.println("method name"+method.getName());
method=c.getDeclaredMethod("printMethodName2");//printMethodName2 //是private型
System.out.println("method name"+method.getName());
cons=c.getConstructor(new Class[] {int.class,int.class});
System.out.println("cons "+cons.getName() +" "+cons.getTypeParameters());
}
public static void main(String[] args) {
GetFieldSimple gg = new GetFieldSimple(100, 200);
printHeight(gg);
}
}
運行後會報java.lang.NoSuchFieldException: width這個錯誤,這是因為width是一個private類型。
c.getField(“***”)這個方法可以返回c所表示的類或介面的所有的公用欄位。
c.getDeclaredField("xxxx");返回已聲明的field(包括private類型)。
Method中的getMethod() 獲得public方法和getDelcaredMethod()可以獲得所有。
static欄位可以直接從類中取而不需要從對象中取等
更詳細的用法,可以去多看看API。這個只是最簡單的一個例子。