【Java】【反射】__Java

來源:互聯網
上載者:User

1.Java的反射機制的概念:

在Java運行時環境中,對於任意一個類,能否知道這個類的哪些屬性和方法。對於任意一個對象,能否調用它的任意一個方法。答案是肯定的。這種動態擷取類的資訊以及動態調用對象的方法的功能來自於Java語言的反射(Reflection)機制。
Reflection是Java被視為動態(准動態)語言的一個關鍵性質。這個機制允許程式在運行時透過Reflection APIs取得任何一個已知名稱的class的內部資訊,包括modifiers(諸如static、public等等)、superclass(例如Object)、實現interfaces(例如Serializable),也包括fields和methods的所有資訊,並可於運行時改變fields內容或調用methods。

一般而言,開發人員社群說到動態語言,大致認同一個定義是:“程式運行時,允許改變程式結構或變數類型,這種語言稱為動態語言”。從這個觀點看,Perl、Python、Ruby是動態語言,C++、Java、C#不是動態語言。

儘管在這樣的定義與分類下Java不是動態語言,它卻有著一個非常突出的動態相關機制:Reflection。這個字的意思是“反射、映像、倒影”,用在Java身上指的是我們可以於運行時載入、探知、使用編譯期間完全未知的classes。換句話說,Java程式可以載入一個運行時才得知名稱的class,獲悉其完整構造(但不包括methods的定義),並產生其對象實體、或對其fields設值、或喚起其methods。這種“看透class”的能力(the ability of the program to examine itself)被稱為introspection(內省、內觀、反省)。Reflection和introspection是常被並提的兩個術語。


2.Java反射機制主要提供了以下功能: (1)在運行時判斷任意一個對象所屬的類; (2)在運行時構造任意一個類的對象; (3)在運行時判斷任意一個類所具有的成員變數和方法; (4)在運行時調用任意一個對象的方法。


3.Java Reflection APIs 簡介: 在JDK中,主要由以下類來實現Java反射機制,這些類都位於java.lang.reflect包中 –Class類:代表一個類 –Field類:代表類的成員變數(成員變數也成為類屬性) –Method類:代表類的方法 –Constructor類:代表類的構造方法 –Array類:提供動態建立數組,以及訪問數組的元素的靜態方法
Java中,無論產生某個類的多少個對象,這些對象都會對應於同一個Class對象。
兩個例子程式:

<span style="font-family:Comic Sans MS;font-size:18px;">import java.lang.reflect.Method;public class DumpMethods {public static void main(String[] args) throws Exception{//Class對象描述了某個特定的類對象Class<?> classType = Class.forName("java.lang.String");//通過反射擷取到所有的方法Method[] methods = classType.getDeclaredMethods();//列印所有的方法for(Method m : methods){System.out.println(m);}}}</span>

<span style="font-family:Comic Sans MS;font-size:18px;">import java.lang.reflect.Method;public class InvokeTester {public int add(int parm1, int parm2) {return parm1 + parm2;}public String echo(String message) {return "hello:" + message;}public static void main(String[] args) throws Exception {// InvokeTester test = new InvokeTester();// System.out.println(test.add(1, 2));// System.out.println(test.echo("Java"));Class<?> classType = InvokeTester.class;//通過反射產生一個InvokeTester類型的對象Object o = classType.newInstance();//通過反射擷取到add方法Method addMethod = classType.getMethod("add", new Class[] { int.class,int.class });//調用對象的add方法並把參數傳進去System.out.println(addMethod.invoke(o,new Object[]{1,2}));//通過反射擷取到echo方法Method echoMethod = classType.getMethod("echo", new Class[]{String.class});//調用對象的echo方法並把參數傳進去System.out.println(echoMethod.invoke(o, new Object[]{"Java"}));}}</span>

要想使用反射,首先需要獲得待處理類或對象所對應的Class對象。
擷取某個類或對象所對應的Class對象的3種方式: 1)使用Class類的靜態方法forName,如Class.forName("java.lang.String"); 2)使用.class文法,如String.class; 3)使用對象的getClass方法,如String s = "abc"; Class<?> classType = s.getClass();
若想通過類的不帶參數的構造方法來產生對象,我們有兩種方式: 1)先獲得Class對象,然後通過該Class對象的newInstance方法直接獲得即可。如 Class<?> classType = String.class;  Object o = classType.newInstance(); 2)先獲得Class對象,然後通過該Class對象獲得所對應的Constructor對象,再通過該Constructor對象的newInstance方法產生。如 Class<?> classType = Customer.class; Constructor constructor  =classType.getConstructor(new Class[]{}); Object o1 = constructor.newInstance(new Object[]{});
若想通過類的帶參數的構造方法來產生對象,只能使用下面這種方式: Class<?> classType = Customer.class;
Constructor constructor2  = classType.getConstructor(new Class[]{String.class,int.class});
Object o2 = constructor.newInstance(new Object[]{"張三",20});

稍完整一點的樣本:
<span style="font-family:Comic Sans MS;font-size:18px;">import java.lang.reflect.Field;import java.lang.reflect.Method;public class ReflectTest {// 該方法實現對Customer的拷貝public static Object copy(Object object) throws Exception {Class<?> classType = object.getClass();Object objectCopy = classType.getConstructor(new Class[] {}).newInstance(new Object[] {});Field[] fields = classType.getDeclaredFields();for (Field field : fields) {String name = field.getName();String firstLetter = name.substring(0, 1).toUpperCase();// 將屬性的首字母轉換為大寫String getMethodName = "get" + firstLetter + name.substring(1);String setMethodName = "set" + firstLetter + name.substring(1);Method getMethod = classType.getMethod(getMethodName,new Class[] {});Method setMethod = classType.getMethod(setMethodName,new Class[] { field.getType() });Object value = getMethod.invoke(object, new Object[] {});setMethod.invoke(objectCopy, new Object[] { value });}return objectCopy;}public static void main(String[] args) throws Exception {Customer c = new Customer("Tom", 20);c.setId(1L);Object o = copy(c);Customer customerCopy = (Customer) o;System.out.println(customerCopy.getId() + "," + customerCopy.getName()+ "," + customerCopy.getAge());}}class Customer {private long id;private String name;private int age;public Customer() {}public Customer(String name, int age) {this.name = name;this.age = age;}public long getId() {return id;}public void setId(long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}</span>

Java.lang.Array類提供了動態建立和訪問數組元素的各種靜態方法。 第一個樣本:
<span style="font-family:Comic Sans MS;font-size:18px;">import java.lang.reflect.Array;public class ArrayTester {public static void main(String[] args) {Class<?> classType = String.class;Object array = Array.newInstance(classType, 10);Array.set(array, 5, "hello");String s = (String) Array.get(array, 5);System.out.println(s);}}</span>

第二個樣本: Integer.TYPE 返回的是int所對應的Class對象
Integer.class 返回的是Integer所對應的Class對象
<span style="font-family:Comic Sans MS;font-size:18px;">import java.lang.reflect.Array;public class ArrayTester2 {public static void main(String[] args) {int[] dims = new int[]{5,10,15};Object array = Array.newInstance(Integer.TYPE, dims);Object arrayObj = Array.get(array, 3);//Class<?> classType = arrayObj.getClass().getComponentType();////System.out.println(classType);arrayObj = Array.get(arrayObj, 5);Array.set(arrayObj, 10, 37);int[][][] arrayCast = (int[][][]) array;System.out.println(arrayCast[3][5][10]);}}</span>


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.