JAVA反射機制是在運行狀態中對於任意一個類都能夠得到這個類的所有屬性和方法;對於任意一個對象都能夠調用它的任意一個方法;這種動態獲取的信息以及動態調用對象的方法的功能稱為java語言的反射機制
概括一下:
反射就是讓你可以通過名稱來得到對象(類屬性方法)的技術
例如我們可以通過類名來生成一個類的實例;
知道了方法名就可以調用這個方法;知道了屬性名就可以訪問這個屬性的值
獲取類對應的Class對象
運用(已知對象)getClass():Object類中的方法每個類都擁有此方法
如: String str = new String();
Class strClass = strgetClass();運用(已知子類的class) ClassgetSuperclass():Class類中的方法返回該Class的父類的Class;運用(已知類全名):ClassforName() 靜態方法運用(已知類): 類名class
通過類名來構造一個類的實例
a調用無參的構造函數:
Class newoneClass = ClassforName(類全名); newoneClassnewInstance();
b調用有參的構造函數我們可以自定義一個函數
public Object newInstance(String className Object[] args) throws Exception {
//args為參數數組
Class newoneClass = ClassforName(className); //得到參數的Class數組(每個參數的class組成的數組)由此來決定調用那個構造函數Class[] argsClass = new Class[argslength]; for (int i = j = argslength; i < j; i++) { argsClass[i] = args[i]getClass();
}
Constructor cons = newoneClassgetConstructor(argsClass); //根據argsClass選擇函數return consnewInstance(args); //根據具體參數實例化對象
}
得到某個對象的屬性
a非靜態屬性:首先得到class然後得到這個class具有的field然後以具體實例為參數調用這個field
public Object getProperty(Object owner String fieldName) throws Exception { Class ownerClass = ownergetClass();//首先得到class Field field = ownerClassgetField(fieldName); //然後得到這個class具有的field也可以通過getFields()得到所有的field Object property = fieldget(owner); //owner指出了取得那個實例的這個屬性值如果這個屬性是非公有的這裡會報IllegalAccessException
return property;
}
b靜態屬性
只有最後一步不同由於靜態屬性屬於這個類所以只要在這個類上調用這個field即可Object property = fieldget(ownerClass);
執行某對象的方法
public Object invokeMethod(Object owner String methodName Object[] args) throws Exception { Class ownerClass = ownergetClass(); //也是從class開始的//得到參數的class數組相當於得到參數列表的類型數組來取決我們選擇哪個函數
Class[] argsClass = new Class[argslength]; for (int i = j = argslength; i < j; i++) { argsClass[i] = args[i]getClass();
}
//根據函數名和函數類型來選擇函數
Method method = ownerClassgetMethod(methodName argsClass); return methodinvoke(owner args);//具體實例下具體參數值下調用此函數
}
執行類的靜態方法
和上面的相似只是最後一行不需要指定具體實例
return methodinvoke(null args);
判斷是否為某個類的實例
public boolean isInstance(Object obj Class cls) { return clsisInstance(obj);
}
測試bean類:SimpleBeanjava
Java代碼
package comroyzhoubean;
public class SimpleBean {
private String name;
private String[] hobby;
public SimpleBean() {
}
public SimpleBean(String name String[] hobby) { thisname = name; thishobby = hobby;
}
public void setName(String name) {
thisname = name;
}
public String getName() {
return thisname;
}
public void setHobby(String[] hobby) {
thishobby = hobby;
}
public String[] getHobby() {
return thishobby;
}
public String toString() {
String returnValue = supertoString() + \n; returnValue += name:= + thisname + \n; if(thishobby != null) {
returnValue += hobby:;
for(String s : thishobby) { returnValue += s + ;
}
returnValue += \n;
}
return returnValue;
}
}
package comroyzhoubean;
public class SimpleBean {
private String name;
private String[] hobby;
public SimpleBean() {
}
public SimpleBean(String name String[] hobby) { thisname = name; thishobby = hobby;
}
public void setName(String name) {
thisname = name;
}
public String getName() {
return thisname;
}
public void setHobby(String[] hobby) {
thishobby = hobby;
}
public String[] getHobby() {
return thishobby;
}
public String toString() {
String returnValue = supertoString() + \n; returnValue += name:= + thisname + \n; if(thishobby != null) {
returnValue += hobby:;
for(String s : thishobby) { returnValue += s + ;
}
returnValue += \n;
}
return returnValue;
}
}
反射測試類:ReflectTestjava
Java代碼
package comroyzhoubean;
import javalangreflectConstructor; import javalangreflectField; import javalangreflectMethod;
public class ReflectTest {
public static void main(String[] args) throws Exception {
Class clazz = SimpleBeanclass;
//使用無參構造函數實例化bean
SimpleBean sb = (SimpleBean)clazznewInstance(); Systemoutprintln(sb);
//使用有參構造函數實例化bean
Constructor constructor = clazzgetConstructor(new Class[]{Stringclass String[]class}); sb = (SimpleBean)constructornewInstance(new Object[]{royzhounew String[]{footballbasketball}}); Systemoutprintln(sb);
//為name字段設置值
Field field = clazzgetDeclaredField(name); fieldsetAccessible(true); //避免private不可訪問拋出異常fieldset(sb royzhou); Systemoutprintln(modify name using Field:= + sbgetName() + \n);
//列出類SimpleBean的所有方法
Method[] methods = clazzgetDeclaredMethods(); Systemoutprintln(get methods of class SimpleBean:);
for(Method method : methods) {
if(setHobbyequals(methodgetName())) {
//動態調用類的方法來為hobby設置值
methodinvoke(sb new Object[]{new String[]{tennisfishing}});
}
Systemoutprintln(methodgetName());
}
Systemoutprintln(\nset by invoke Method); Systemoutprintln(sb);
}
}
package comroyzhoubean;
import javalangreflectConstructor; import javalangreflectField; import javalangreflectMethod;
public class ReflectTest {
public static void main(String[] args) throws Exception {
Class clazz = SimpleBeanclass;
//使用無參構造函數實例化bean
SimpleBean sb = (SimpleBean)clazznewInstance(); Systemoutprintln(sb);
//使用有參構造函數實例化bean
Constructor constructor = clazzgetConstructor(new Class[]{Stringclass String[]class}); sb = (SimpleBean)constructornewInstance(new Object[]{royzhounew String[]{footballbasketball}}); Systemoutprintln(sb);
//為name字段設置值
Field field = clazzgetDeclaredField(name); fieldsetAccessible(true); //避免private不可訪問拋出異常fieldset(sb royzhou); Systemoutprintln(modify name using Field:= + sbgetName() + \n);
//列出類SimpleBean的所有方法
Method[] methods = clazzgetDeclaredMethods(); Systemoutprintln(get methods of class SimpleBean:);
for(Method method : methods) {
if(setHobbyequals(methodgetName())) {
//動態調用類的方法來為hobby設置值
methodinvoke(sb new Object[]{new String[]{tennisfishing}});
}
Systemoutprintln(methodgetName());
}
Systemoutprintln(\nset by invoke Method); Systemoutprintln(sb);
}
}
輸出結果:
comroyzhoubeanSimpleBean@aef
name:=null
comroyzhoubeanSimpleBean@dfc
name:=royzhou
hobby:footballbasketball
modify name using Field:=royzhou
get methods of class SimpleBean:
setHobby
getHobby
getName
toString
setName
set by invoke Method
comroyzhoubeanSimpleBean@dfc
name:=royzhou
hobby:tennisfishing
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26612.html