粗浅看 java反射机制
Java?反射是 Java 被視為動態(或準動態)語言的一個關鍵性質。這個機制允許程序在運 行時透過 Reflection APIs 取得任何一個已知名稱的class 的內部信息,包括其 modifiers( 諸如 public, static 等 )、superclass (例如 Object)、 實現之 interfaces(例如 Cloneable),也包括 fields 和 methods 的所有信息,并可于運行時改變 fields 內容或喚起 methods。
Java 反射機制容許程序在運行時加載、探知、使用編譯期間完全未知的 classes。 換言之,Java 可以加載一個運行時才得知名稱的 class,獲得其完整結構。
JDK 中提供的 Reflection API
Java 反射相關的 API 在包?java.lang.reflect?中,JDK 1.6.0的 reflect 包如下圖:
Member 接口 該接口可以獲取有關類成員(域或者方法)后者構造函數的信息。
AccessibleObject 類
該類是域(field)對象、方法(method)對象、構造函數(constructor)對象 的基礎類。它提供了將反射的對象標記為在使用時取消默認 Java 語言訪問控 制檢查的能力。
Array 類 ? ? 提供動態地生成和訪問 JAVA 數組的方法。
Constructor 類 ? ?提供一個類的構造函數的信息以及訪問類的構造函數的接口。
Field 類???? 提供一個類的域的信息以及訪問類的域的接口。
Method 類??? 提供一個類的方法的信息以及訪問類的方法的接口。
Modifier類 ? ?提供了 static 方法和常量,對類和成員訪問修飾符進行解碼。
Proxy?類???? 提供動態地生成代理類和類實例的靜態方法。
JAVA 反射機制提供了什么功能?
Java 反射機制提供如下功能: 在運行時判斷任意一個對象所屬的類 在運行時構造任意一個類的對象
在運行時判段任意一個類所具有的成員變量和方法 在運行時調用任一個對象的方法
在運行時創建新類對象
在使用 Java 的反射功能時,基本首先都要獲取類的 Class 對象,再通過 Class 對象獲取 其他的對象。
這里首先定義用于測試的類:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <span style="font-size:18px;">classType{ ???????publicintpubIntField; ???????publicString pubStringField; ???????privateintprvIntField; ????????publicType(){ ??????????Log("Default Constructor"); ???} ??????????Type(intarg1, String arg2){ ??????????pubIntField = arg1; ??????????pubStringField = arg2; 13 ????????Log("Constructor with parameters"); 15? } ????publicvoidsetIntField(intval) { ?????this.prvIntField = val; 19?? } ?????????publicintgetIntField() { ????returnprvIntField; ?????} ?????????privatevoidLog(String msg){ ?????????System.out.println("Type:"+ msg); ???} ?}</span> |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <span style="font-size:18px;">?? classExtendTypeextendsType{ ?????publicintpubIntExtendField; ?????publicString pubStringExtendField; ?????privateintprvIntExtendField; <span style="white-space:pre">??? </span>publicExtendType(){ ?} Log("Default Constructor"); } ExtendType(intarg1, String arg2){ pubIntExtendField = arg1; pubStringExtendField = arg2; Log("Constructor with parameters"); } publicvoidsetIntExtendField(intfield7) { this.prvIntExtendField = field7; } publicintgetIntExtendField() { returnprvIntExtendField; } privatevoidLog(String msg){ System.out.println("ExtendType:"+ msg); }</span> |
1、獲取類的 Class 對象
Class 類的實例表示正在運行的 Java 應用程序中的類和接口。獲取類的 Class 對象有多種方式:
調用 Boolean var1 = true; getClass
運 用 .class語法
運用 static method Class.forName()
| 1 2 | Class<?> classType2 = var1.getClass(); System.out.println(classType2); |
輸出:class java.lang.Boolean
Class<?> classType4 = Boolean.class; System.out.println(classType4);
輸出:class java.lang.Boolean
Class<?> classType5 = Class.forName(“java.lang.Boolean”); System.out.println(classType5);
輸出:class java.lang.Boolean
運用 Class<?> classType3 = Boolean.TYPE
primitive wrapper classes ?的TYPE 語法
這里 返 回 的 是 原 生 類 型 ,和Boolean.class返回的不同
System.out.println(classType3);
輸出:boolean
2、獲取類的 Fields
可以通過反射機制得到某個類的某個屬性,然后改變對應于這個類的某個實例的該屬性值。JAVA 的 Class<T>類提供了幾個方法獲取類的屬性。
public?Field?getField(String?name)
返回一個 Field 對象,它反映此?Class 對象所表示的類或接口的指定公共成員字段
public Field[] getFields()
返回一個包含某些 Field 對象的數組,這些對象反映此?Class 對象所表 示的類或接口的所有可訪問公共字段
public?Field?getDeclared Field(String?name)
返回一個 Field 對象,該對象反映此?Class 對象所表示的類或接口的指定已聲明字段
public Field[] getDeclared Fields()
返回 Field 對象的一個數組,這些對象反映此 Class 對象所表示的類或 接口所聲明的所有字段
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <span style="font-size:18px;">Class<?> classType = ExtendType.class; // 使用 getFields 獲取屬性 Field[] fields = classType.getFields(); for(Field f : fields) { System.out.println(f); } System.out.println(); // 使用 getDeclaredFields 獲取屬性 fields = classType.getDeclaredFie lds(); for(Field f : fields) { System.out.println(f); } ?</span> |
輸出:
public int com.quincy.ExtendType.pubIntExtendField
public java.lang.String com.quincy.ExtendType.pubStringExtendField public int com.quincy.Type.pubIntField
public java.lang.String com.quincy.Type.pubStringField
public int com.quincy.ExtendType.pubIntExtendField
public java.lang.String com.quincy.ExtendType.pubStringExtendField private int com.quincy.ExtendType.prvIntExtendField
可見 getFields和 getDeclaredFields區別:
| 1 2 3 4 5 6 7 8 | <span style="font-size:18px;">public MethodgetMethod(String name, Class<?>... parameterTy pes) public Method[] getMethods( ) public MethodgetDeclared Method(Stringname,Class< ?>... parameterTy pes) public Method[] getDeclared Methods()</span> |
getFields返回的是申明為 public的屬性,包括父類中定義,
getDeclaredFields返回的是指定類定義的所有定義的屬性,不包括父類的。
3、獲取類的 Method
通過反射機制得到某個類的某個方法,然后調用對應于這個類的某個實例的該方法
Class<T>類提供了幾個方法獲取類的方法。
| 1 2 3 4 5 6 7 | <span style="font-size:18px;">public MethodgetMethod(String name, Class<?>... parameterTy pes) public Method[] getMethods( ) public MethodgetDeclared Method(Stringname,Class< ?>... parameterTy pes) public Method[] getDeclared Methods()</span> |
返回一個 Method 對象,它反映此 Class 對象所表示的類或接口的指定公共成員方法;
返回一個包含某些 Method 對象的數組,這些對象反映此Class 對象所表 示的類或接口(包括那些由該類或接口聲明的以及從超類和超接口繼承的那 些的類或接口)的公共 member 方法;
返回一個 Method 對象,該對象反映此Class 對象所表示的類或接口的指 定已聲明方法;
返回 Method對象的一個數組,這些對象反映此 Class 對象表示的類或接 口聲明的所有方法,包括公共、保護、默認(包)訪問和私有方法,但不包 括繼承的方法。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <span style="font-size:18px;">?? // 使用 getMethods 獲取函數 ???Class<?> classType = ExtendType.class; ???Method[] methods = classType.getMethods(); ????for(Method m : methods)5 { ??????System.out.println(m); ??} ??System.out.println(); ?// 使用 getDeclaredMethods 獲取函數 ?methods = classType.getDeclaredMethods(); ??for(Method m : methods) { ?????System.out.println(m); ?}</span> |
輸出:
public void com.quincy.ExtendType.setIntExtendField(int) public int com.quincy.ExtendType.getIntExtendField() public void com.quincy.Type.setIntField(int)
public int com.quincy.Type.getIntField()
public final native void?? java.lang.Object.wait(long)??? throws java.lang.InterruptedException
public final void ? java.lang.Object.wait() ?throws java.lang.InterruptedException
public final void ? java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang.Object) public java.lang.String java.lang.Object.toString() public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass() public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll() private void com.quincy.ExtendType.Log(java.lang.String) public void com.quincy.ExtendType.setIntExtendField(int) public int com.quincy.ExtendType.getIntExtendField()
4、獲取類的 Constructor
通過反射機制得到某個類的構造器,然后調用該構造器創建該類的一個實例Class<T>類提供了幾個方法獲取類的構造器。
public Constructor< T>
返回一個 Constructor 對象,它反映此 Class對象所表示的類的指定 公共構造方法
| 1 2 3 4 5 6 7 | <span style="font-size:18px;">getConstruct or(Class<?>. .. parameterTyp es) public Constructor< ?>[] getConstruct ors()</span> |
返回一個包含某些 Constructor 對象的數組,這些對象反映此 Class
對象所表示的類的所有公共構造方法
| 1 2 3 | <span style="font-size:18px;">public Constructor< T> getDeclaredC onstructor(Class<?>... parameterTyp es)</span> |
返回一個 Constructor 對象,該對象反映此 Class對象所表示的類或 接口的指定構造方法
| 1 2 3 4 5 | <span style="font-size:18px;">public Constructor< ?>[] getDeclaredC onstructors( )</span> |
返回 Constructor 對象的一個數組,這些對象反映此 Class 對象表示 的類聲明的所有構造方法。它們是公共、保護、默認(包)訪問和私有構造方法
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <span style="font-size:18px;">?? // 使用 getConstructors 獲取構造器 ???Constructor<?>[] constructors = classType.getConstructors(); ????for(Constructor<?> m : constructors){ ??????System.out.println(m); ?} ?System.out.println(); ?// 使用 getDeclaredConstructors 獲取構造器 ?constructors = classType.getDeclaredConstructors(); ??for(Constructor<?> m : constructors)? { System.out.println(m); } ?輸出: ?publiccom.quincy.ExtendType() ?publiccom.quincy.ExtendType() ?com.quincy.ExtendType(int,java.lang.String)<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">?</span></span> |
5、新建類的實例
通過反射機制創建新類的實例,有幾種方法可以創建新類的實例,調用無自變量
①、調用類的 Class對象的 newInstance方法,該方法會調用對象的默認ctor構造器,如果沒有默認構造器,會調用失敗.
| 1 | <span style="font-size:18px;">Class<?> classType = ExtendType.class; Object inst = classType.newInstance(); System.out.println(inst);</span> |
輸出:
Type:Default Constructor ExtendType:Default Constructor com.quincy.ExtendType@d80be3
②、調用默認 Constructor 對象的 newInstance 方法
| 1 2 3 | <span style="font-size:18px;">Class<?> classType = ExtendType.class; Constructor<?>? constructor1 = classType.getConstructor(); Object inst = constructor1.newInstance(); System.out.println(inst);</span> |
輸出:
Type:Default Constructor ExtendType:Default Constructor com.quincy.ExtendType@1006d75
③、調用帶參數 Constructor 對象的 newInstance 方法
| 1 2 3 | <span style="font-size:18px;">Constructor<?> constructor2 = classType.getDeclaredConstructor(int.class, String.class); Object inst = constructor2.newInstance(1, "123"); System.out.println(inst);</span> |
輸出:
Type:Default Constructor ExtendType:Constructor with parameters com.quincy.ExtendType@15e83f9
6、調用類的函數
通過反射獲取類 Method 對象,調用 Field 的 Invoke 方法調用函數。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <span style="font-size:18px;">Class<?> classType = ExtendType.class; Object inst = classType.newInstance(); Method??? logMethod?? = classType.<STRONG>getDeclaredMethod</STRONG>("Log", String.class); logMethod.invoke(inst,"test"); 輸出: Type:Default Constructor ExtendType:Default Constructor <FONT color=#ff0000>Class com.quincy.ClassT can not accessa member ofclasscom.quincy.ExtendType with modifiers"private"</FONT> <FONT color=#ff0000>上面失敗是由于沒有權限調用 private 函數,這里需要設置 Accessible 為 true;</FONT> Class<?> classType = ExtendType.class; Object inst = classType.newInstance(); Method????? logMethod????? =???? classType.getDeclaredMethod("Log", String.class); <FONT color=#ff0000>logMethod.setAccessible(true);</FONT> logMethod.invoke(inst,"test");</span> |
7、設置/獲取類的屬性值
通過反射獲取類的 Field 對象,調用 Field 方法設置或獲取值
| 1 2 3 4 5 6 7 | <span style="font-size:18px;">Class<?> classType = ExtendType.class; Object inst = classType.newInstance(); Field intField = classType.getField("pubIntExtendField"); intField.<STRONG>setInt</STRONG>(inst,100); intvalue = intField.<STRONG>getInt</STRONG>(inst); </span> |
動態創建代理類?
代理模式:代理模式的作用=為其他對象提供一種代理以控制對這個對象的訪問。 代理模式的角色:
抽象角色:聲明真實對象和代理對象的共同接口 代理角色:代理角色內部包含有真實對象的引用,從而可以操作真實對象。真實角色:代理角色所代表的真實對象,是我們最終要引用的對象。?動態代理:
java.lang.re flect.Proxy
Proxy提供用于創建動態代理類和實例的靜態方法,它還是由這些方法創建 的所有動態代理類的超InvocationHandler是代理實例的調用處理程序 實現的接口,每個代理實例都具有一個關聯的調用處理程序。對代理實例調用方法時,將對方法調用進行編碼并將其指派到 它的調用處理程序的 invoke 方法。
動態 Proxy 是這樣的一種類:
它是在運行生成的類,在生成時你必須提供一組 Interface給它,然后該 class 就宣稱 它實現了這些interface。你可以把該 class 的實例當作這些 interface 中的任何一個 來用。當然,這個 DynamicProxy其實就是一個 Proxy,它不會替你作實質性的工作,在生成它的實例時你必須提供一個 handler,由它接管實際的工作。
在使用動態代理類時,我們必須實現 InvocationHandler接口
步驟:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <span style="font-size:18px;">//1、定義抽象角色 public interface Subject { public void Request(); } //2、定義真實角色 public class RealSubject implements Subject { @Override public void Request() { // TODO Auto-generated method stub System.out.println("RealSubject"); } } //3、定義代理角色 public class DynamicSubject implements InvocationHandler { private Objectsub; public DynamicSubject(Object obj){ this.sub = obj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{ // TODO Auto-generated method stub System.out.println("Method:"+ method + ",Args:" + args); method.invoke(sub, args); return null; } } //4、通過 Proxy.newProxyInstance 構建代理對象 RealSubject realSub = new RealSubject(); InvocationHandler handler = new DynamicSubject(realSub); Class<?> classType = handler.getClass(); Subject??? sub? = (Subject)Proxy.newProxyInstance(classType.getClassLoader(), realSub.getClass().getInterfaces(), handler); System.out.println(sub.getClass()); //5、通過調用代理對象的方法去調用真實角色的方法。 sub.Request();</span> |
輸出:
class $Proxy0 新建的代理對象,它實現指定的接口
Method:public ? abstract ? void DynamicProxy.Subject.Request(),Args:null
RealSubject 調用的真實對象的方法
本篇文章依舊采用小demo來說明,因為我始終覺的,案例驅動是最好的,要不然只看理論的話,看了也不懂,不過建議大家在看完文章之后,在回過頭去看看理論,會有更好的理解。
下面開始正文。
【案例1】通過一個對象獲得完整的包名和類名
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <span style="font-size:18px;">packageReflect; /** * 通過一個對象獲得完整的包名和類名 * */ classDemo{ //other codes... } classhello{ publicstaticvoidmain(String[] args) { Demo demo=newDemo(); System.out.println(demo.getClass().getName()); } } </span> |
【運行結果】:Reflect.Demo
添加一句:所有類的對象其實都是Class的實例。
【案例2】實例化Class類對象
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <span style="font-size:18px;">packageReflect; classDemo{ //other codes... } classhello{ publicstaticvoidmain(String[] args) { Class<?> demo1=null; Class<?> demo2=null; Class<?> demo3=null; try{ //一般盡量采用這種形式 demo1=Class.forName("Reflect.Demo"); }catch(Exception e){ e.printStackTrace(); } demo2=newDemo().getClass(); demo3=Demo.class; System.out.println("類名稱?? "+demo1.getName()); System.out.println("類名稱?? "+demo2.getName()); System.out.println("類名稱?? "+demo3.getName()); } } </span> |
【運行結果】:
類名稱???Reflect.Demo
類名稱???Reflect.Demo
類名稱???Reflect.Demo
【案例3】通過Class實例化其他類的對象?通過無參構造實例化對象
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | <span style="font-size:18px;">package Reflect; class Person{ ?public String getName(){ ?return name; ??} ?public void setName(String name) { this.name = name;?? } public int getAge() { return age; ?} public void setAge(intage) { this.age = age;??? } @Override ?????public String toString(){ ??????????return"["+this.name+"? "+this.age+"]"; ????} ?private String name; ?private int age; ?} class hello{ public static void main(String[] args) { } Class<?> demo=null; try{ demo=Class.forName("Reflect.Person"); }catch(Exception e) { e.printStackTrace(); } Person per=null; try{ per=(Person)demo.newInstance(); }catch(InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch(IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } per.setName("Rollen"); per.setAge(20); System.out.println(per); }</span> |
【運行結果】:
[Rollen20]
但是注意一下,當我們把?Person中的默認的無參構造函數取消的時候,比如自己定義只定義一個有參數?的構造函數之后,會出現錯誤:
比如我定義了一個構造函數:
| 1 2 3 4 | <span style="font-size:18px;"> public Person(String name,intage) { ?????this.age=age; ?????this.name=name; }</span> |
然后繼續運行上面的程序,會出現:
| 1 2 3 4 5 6 | <span style="font-size:18px;">java.lang.InstantiationException:Reflect.Person atjava.lang.Class.newInstance0(Class.java:340) atjava.lang.Class.newInstance(Class.java:308) atReflect.hello.main(hello.java:39) Exceptioninthread"main"java.lang.NullPointerException atReflect.hello.main(hello.java:47)</span> |
所以大家以后再編寫使用 Class 實例化其他類的對象的時候,一定要自己定義無參的構造函數
【案例】通過 Class 調用其他類中的構造函數 (也可以通過這種方式通過 Class 創建其他類的對象)
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | <span style="font-size:18px;">package Reflect; import java.lang.reflect.Constructor; class Person{ public Person() { ?} ?publicPerson(String name){ ?this.name=name; } ?public Person(intage){ ?this.age=age; } public Person(String name,intage) { ?} this.age=age; this.name=name; } publicString getName() { returnname; } publicintgetAge() { returnage; } @Override publicString toString(){ return"["+this.name+" "+this.age+"]"; } private String name; private int age; class hello{ ?public static void main(String[] args) { Class<?> demo=null; ???try{ demo=Class.forName("Reflect.Person"); ?}catch(Exception e) { ?e.printStackTrace(); ?} ?Person per1=null; ?Person per2=null; ?Person per3=null; ?Person per4=null; //取得全部的構造函數 ?Constructor<?>? cons[]=demo.getConstructors(); ?try{ per1=(Person)cons[0].newInstance(); per2=(Person)cons[1].newInstance("Rollen"); per3=(Person)cons[2].newInstance(20); per4=(Person)cons[3].newInstance("Rollen",20); }catch(Exception e){ e.printStackTrace(); } System.out.println(per1); System.out.println(per2); System.out.println(per3); System.out.println(per4); }</span> |
【運行結果】:
[null0]
[Rollen0]
[null20]
[Rollen20]
【案例】 返回一個類實現的接口:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | <span style="font-size:18px;">package Reflect; ?interfaceChina{ ?publicstaticfinalString? name="Rollen"; ???????publicstatic? int age=20; ???????publicvoidsayChina(); ???????publicvoidsayHello(String? name,intage); ???} class Person implements China{ ??????public Person() { ???} ?????publicPerson(String sex){ ???????????this.sex=sex; ????} ??????publicString getSex(){ ????????????returnsex; ????} ??????publicvoidsetSex(String sex) { ??????this.sex = sex; 22??? } ??????@Override ??????publicvoidsayChina(){ ???????????System.out.println("hello? ,china"); ?????} ?????@Override ??????publicvoidsayHello(String? name,intage){ ????????????System.out.println(name+"? "+age); ????} ???privateString sex; ??} ?class hello{ ???????publicstaticvoidmain(String[] args) { ?????????????Class<?> demo=null; ?????????????try{ ?????????????????demo=Class.forName("Reflect.Person"); ????????????}catch(Exception e) { ?????????????????e.printStackTrace(); ?} } //保存所有的接口 Class<?>? intes[]=demo.getInterfaces(); for(inti =0; i < intes.length; i++) { System.out.println("實現的接口?? "+intes[i].getName()); } }</span> |
【運行結果】:
實現的接口???Reflect.China
(注意,以下幾個例子,都會用到這個例子的?Person類,所以為節省篇幅,此處不再粘貼?Person的代?碼部分,只粘貼主類?hello的代碼)
【案例】:取得其他類中的父類
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <span style="font-size:18px;">class hello{ public static void main(String[] args) { Class<?> demo=null; try{ demo=Class.forName("Reflect.Person"); }catch(Exception e) { e.printStackTrace(); } //取得父類 Class<?>? temp=demo.getSuperclass(); System.out.println("繼承的父類為:?? "+temp.getName()); } } </span> |
【運行結果】
繼承的父類為:???java.lang.Object
【案例】:獲得其他類中的全部構造函數 這個例子需要在程序開頭添加importjava.lang.reflect.*;然后將主類編寫為:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <span style="font-size:18px;">class hello{ public static void main(String[] args) { Class<?> demo=null; try{ demo=Class.forName("Reflect.Person"); }catch(Exception e) { e.printStackTrace(); } Constructor<?>cons[]=demo.getConstructors(); for(inti =0; i < cons.length; i++) { System.out.println("構造方法:? "+cons[i]); } } }</span> |
【運行結果】:
構造方法:public?Reflect.Person()
構造方法:publicReflect.Person(java.lang.String)
但是細心的讀者會發現,上面的構造函數沒有?public或者?private這一類的修飾符下面這個例子我們就來獲取修飾符
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <span style="font-size:18px;"> class hello{ //構造方法 ?} publicstaticvoidmain(String[] args) { Class<?> demo=null; try{ demo=Class.forName("Reflect.Person"); }catch(Exception e) { e.printStackTrace(); } Constructor<?>cons[]=demo.getConstructors(); for(inti =0; i < cons.length; i++) { Class<?>? p[]=cons[i].getParameterTypes(); System.out.print("構造方法:?????????????????????? "); intmo=cons[i].getModifiers(); System.out.print(Modifier.toString(mo)+"? "); System.out.print(cons[i].getName()); System.out.print("("); for(intj=0;j<p.length;++j){ System.out.print(p[j].getName()+"? arg"+i); if(j<p.length-1){ System.out.print(","); } } System.out.println("){}"); } }</span> |
【運行結果】:
構造方法:?publicReflect.Person(){}
構造方法:?publicReflect.Person(java.lang.Stringarg1){}
有時候一個方法可能還有異常。下面看看:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | <span style="font-size:18px;"> class hello{ ??publicstaticvoidmain(String[] args) { ????????????Class<?> demo=null; ????????????try{ ???????????????????demo=Class.forName("Reflect.Person"); ??????????????}catch(Exception e) { ????????????????????e.printStackTrace(); ?????????} ??????????????Method? method[]=demo.getMethods(); ?????????????for(inti=0;i<method.length;++i){ ??????????????????Class<?>? returnType=method[i].getReturnType(); ??????????????????Class<?>? para[]=method[i].getParameterTypes(); ??????????????????inttemp=method[i].getModifiers(); ?????????????????System.out.print(Modifier.toString(temp)+"? "); ????????????????System.out.print(returnType.getName()+"? "); ?????????????????System.out.print(method[i].getName()+" "); ?????????????????System.out.print("("); ??????????????????for(intj=0;j<para.length;++j){ ???????????????????????System.out.print(para[j].getName()+"? "+"arg"+j); ?????????????????????if(j<para.length-1){ ????????????????????????????System.out.print(","); ??????????????} ????????????} ?????????????????Class<?>? exce[]=method[i].getExceptionTypes(); ???????????????if(exce.length>0){ ??????????????????????System.out.print(") throws "); ??????????????????????for(intk=0;k<exce.length;++k){ ???????????????????????????System.out.print(exce[k].getName()+" "); ??????????????????????????if(k<exce.length-1){ ?????????????????????????????????System.out.print(","); ????????????????} ??????????????} ?} }else{ System.out.print(")") } System.out.println(); } }</span> |
【運行結果】:
| 1 2 3 4 5 6 7 8 9 10 | <span style="font-size:18px;">public java.lang.StringgetSex() public void setSex(java.lang.Stringarg0)publicvoidsayChina () public void sayHello (java.lang.String arg0,int arg1) public final native void wait (long arg0) throwsjava.lang.InterruptedException public final void wait()throwsjava.lang.InterruptedException public final void wait(longarg0,intarg1)throwsjava.lang.InterruptedException public boolean equals(java.lang.Objectarg0)publicjava.lang.StringtoString() public native int hashCode() public final native java.lang.ClassgetClass () public final native void notify () public final native void notifyAll()</span> |
【案例】接下來讓我們取得其他類的全部屬性吧,最后我講這些整理在一起,也就是通過class取得一個?類的全部框架
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <span style="font-size:18px;"> class hello { ???????public static void main(String[] args) { ?????????Class<?> demo =null; ?????????try{????????????? ?demo = Class.forName("Reflect.Person"); ??????????}catch(Exception e) { ????????????e.printStackTrace(); ????????} ???????System.out.println("===============???? 本????? 類????? 屬????? 性 ?========================"); ????// 取得本類的全部屬性 ????????Field[] field = demo.getDeclaredFields(); ???????????for(int i =0; i < field.length; i++) { 14???? // 權限修飾符 ????????????????int mo = field[i].getModifiers(); ????????????????String priv = Modifier.toString(mo); ??????????// 屬性類型 ??????????????Class<?> type = field[i].getType(); ????????????????System.out.println(priv +" "+type.getName() +" " ???????????????+ field[i].getName() +";"); 21?? } ???????System.out.println("=============== 實 現 的 接 口 或 者 父 類 的 屬 性 ??========================"); ??????// 取得實現的接口或者父類的屬性 ???????????Field[] filed1 = demo.getFields(); ????????????for(intj =0; j < filed1.length; j++) { 27??? // 權限修飾符 ???????????????int mo = filed1[j].getModifiers(); ??????????????????String priv = Modifier.toString(mo); ??????????// 屬性類型 ????????????????Class<?> type = filed1[j].getType(); ?????????????????System.out.println(priv +" "+type.getName() +" "+ filed1[j].getName() +";") } }</span> |
【運行結果】:
===============本類屬性========================
private?java.lang.String?sex;
===============實現的接口或者父類的屬性========================
public?static?final?java.lang.String name; public static final int age;
【案例】其實還可以通過反射調用其他類中的方法:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <span style="font-size:18px;">? class hello { ??public static void main(String[] args) { ??????????????Class<?> demo =null; ??????????????try{ ???????????????????demo = Class.forName("Reflect.Person"); ????????????}catch(Exception e) { ?????????????????e.printStackTrace(); ????????} ??????????????try{ ?????????????????//調用 Person 類中的 sayChina 方法 ??????????????????Method? method=demo.getMethod("sayChina"); ??????????????????method.invoke(demo.newInstance()); ????????????????//調用 Person 的 sayHello 方法 ????????????????method=demo.getMethod("sayHello", String.class,int.class); ?} }catch(Exception e) { e.printStackTrace(); } }</span> |
【運行結果】:
hello,chinaRollen20
動態代理
【案例】首先來看看如何獲得類加載器:
| 1 2 3 4 5 6 7 8 | <span style="font-size:18px;">class test{ ?} ?class hello{ public static void main(String[] args) { test t=newtest(); System.out.println("類加載器"+t.getClass().getClassLoader().getClass().getName()); } }</span> |
【程序輸出】:
類加載器?sun.misc.Launcher$AppClassLoader
其實在java中有三種類類加載器。
1)BootstrapClassLoader此加載器采用c++編寫,一般開發中很少見。
2)ExtensionClassLoader用來進行擴展類的加載,一般對應的是jre\lib\ext目錄中的類3)AppClassLoader?加載?classpath?指定的類,是最常用的加載器。同時也是java?中默認的加載器。?如果想要完成動態代理,首先需要定義一個?InvocationHandler接口的子類,已完成代理的具體操作。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | <span style="font-size:18px;"> package Reflect; ?import java.lang.reflect.*; ?//定義項目接口 ??interface Subject { ?public String say(String name,intage); 7?? } ?// 定義真實項目 ?class RealSubject implements Subject { } @Override public String say(String name,intage) { returnname +"?????????????? "+ age; } ?class MyInvocationHandler implements InvocationHandler { private Object obj =null; public Object bind(Object obj) { this.obj = obj; return Proxy.newProxyInstance(obj.getClass().getClassLoader(), ??} .getClass().getInterfaces(),this); } @Override public Object invoke(Object proxy, Method method,Object[] args) throwsThrowable{ Object temp = method.invoke(this.obj, args); return temp; } ?class hello { ??????public static void main(String[] args) { ???????????MyInvocationHandler demo =newMyInvocationHandler(); ?????????Subject sub = (Subject)demo.bind(newRealSubject()); ?????????String info = sub.say("Rollen",20); ????????System.out.println(info); ????} }</span> |
【運行結果】:?Rollen20
類的生命周期
在一個類編譯完成之后,下一步就需要開始使用類,如果要使用一個類,肯定離不開?? ?JVM。在程序執行中JVM ?通過裝載,鏈接,初始化這3個步驟完成。
類的裝載是通過類加載器完成的,加載器將.class文件的二進制文件裝入JVM的方法區,并且在堆區創 建描述這個類的 ?java.lang.Class ?對象。用來封裝數據。但是同一個類只會被類裝載器裝載以前
鏈接就是把二進制數據組裝為可以運行的狀態。
鏈接分為校驗,準備,解析這3個階段校驗一般用來確認此二進制文件是否適合當前的? ?JVM(版本),準備就是為靜態成員分配內存空間,。并設置默認值
解析指的是轉換常量池中的代碼作為直接引用的過程,直到所有的符號引用都可以被運行程序使用(建立完整的對應關系)
完成之后,類型也就完成了初始化,初始化之后類的對象就可以正常使用了,直到一個對象不再使用之后,將被垃圾回收。釋放空間。
當沒有任何引用指向Class對象時就會被卸載,結束類的生命周期
將反射用于工廠模式 先來看看,如果不用反射的時候,的工廠模式吧:
http://www.cnblogs.com/rollenholt/archive/2011/08/18/2144851.html
反射的用途
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine.This is a relatively advanced feature and should be used only bydevelopers who have a strong graspof the fundamentals of the language.With that caveat in mind, reflection isa powerful technique and can enableapplications toperform operations which would otherwise be impossible.
反射被廣泛地用于那些需要在運行時檢測或修改程序行為的程序中。這是一個相對高級
的特性,只有那些語言基礎非常扎實的開發者才應該使用它。如果能把這句警示時刻放在心里,那么反射機制就會成為一項強大的技術,可以讓應用程序做一些幾乎不可能做到的事情。
反射的缺點
Reflection is powerful, but should not be used indiscriminately. If it is possible to performan operation without using reflection, then it ispreferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.
盡管反射非常強大,但也不能濫用。如果一個功能可以不用反射完成,那么最好就不用。
在我們使用反射技術時,下面幾條內容應該牢記于心:
性能第一?
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed.Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently inperformance-sensitive applications.
反射包括了一些動態類型,所以 JVM 無法對這些代碼進行優化。因此,反射操作的效
率要比那些非反射操作低得多。我們應該避免在經常被 執行的代碼或對性能要求很高的程 序中使用反射。
安全限制?
Reflection requires a runtime permission which may not be presentwhen running under a?security manager. This is in an important consideration for code which has to run in a restrictedsecurity context, such as in an Applet.
使用反射技術要求程序必須在一個沒有安全限制的環境中運行。如果一個程序必須在有
安全限制的環境中運行,如 Applet,那么這就是個問題了。
內部暴露?
Since reflection allows code to perform operations that would be illegal in non-reflective code,?such ?as?accessingprivatefields ?and ?methods,?the ?use?of?reflection ?can ?result?in
unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and thereforemay change behavior with upgradesof the platform.
由于反射允許代碼執行一些在正常情況下不被允許的操作(比如訪問私有的屬性和方
法),所以使用反射可能會導致意料之外的副作用--代碼有功能上的錯誤,降低可移植性。反射代碼破壞了抽象性,因此當平臺發生改變的時候,代碼的行為就有可能也隨著變化。
業務思想
JAVA中反射機制很實用。在不斷地項目實戰中,大家或許才體會到反射的真正強大之處,從很多小的demo中,個人在學習階段時,幾乎沒啥感覺,就是個面熟。參考很多資料,個人的總結不到之處,歡迎交流指正。
from:?http://www.importnew.com/20339.html
總結
以上是生活随笔為你收集整理的粗浅看 java反射机制的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 「深入Java」类型信息:RTTI和反射
- 下一篇: Java反射最佳实践