All About JAVA 如何使用反射(Reflection )

來源:互聯網
上載者:User

來源:http://www.java-tips.org/java-se-tips/java.lang.reflect/how-to-use-reflection-in-java.html

反射是一個很強大的方法用來在運行時對類進行分析,譬如當一個新的類在運行時動態加入到你的應用中,這個時候就可以使用反射機製得到這個類的結構資訊。我們使用一個特殊的類來實現反射: Class.  。 Class類型的對象hold住了類的所有資訊,並且可以使用gette方法來提取我們需要的資訊。下面的例子提取了並在控制台輸出了String類的結構資訊,展示構造方法的名稱,屬性跟方法。

import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method;public class ReflectionExample {  public static void main(String[] args) {    try {      // Creates an object of type Class which contains the information of  建立一個包含String類資訊的Class類型的對象。      // the class String      Class cl = Class.forName("java.lang.String");      // getDeclaredFields() returns all the constructors of the class.       // getDeclaredFields()方法返回類的所有構造方法資訊      Constructor cnst[] = cl.getConstructors();      // getFields() returns all the declared fields of the class.      // getFields()方法返回類中定義的所有屬性資訊      Field fld[] = cl.getDeclaredFields();      // getMethods() returns all the declared methods of the class.      // getMethods()方法返回類中定義的所有方法資訊      Method mtd[] = cl.getMethods();      System.out.println("Name of the Constructors of the String class");      for (int i = 0; i < cnst.length; i++) {        System.out.println(cnst[i].getName());      }      System.out.println("Name of the Declared fields");      for (int i = 0; i < fld.length; i++) {        System.out.println(fld[i].getName());      }      System.out.println("Name of the Methods");      for (int i = 0; i < mtd.length; i++) {        System.out.println(mtd[i].getName());      }    } catch (ClassNotFoundException e) {      e.printStackTrace();    }  }

結果:

Name of the Constructors of the String class / String類構造方法名稱
java.lang.String

……

Name of the Declared fields / 屬性名稱
value
offset
count
hash
serialVersionUID

……

Name of the Methods / 方法名
hashCode
equals
compareTo
compareTo
indexOf
indexOf
indexOf
indexOf

……

 

來源2:http://www.java-tips.org/java-se-tips/java.lang.reflect/invoke-method-using-reflection.html

反射可以用來在運行時動態執行一個方法(即方法名字在運行時才給出或確定),下邊是利用反射實現方法調用的範例程式碼:

import java.lang.reflect.Method;public class RunMthdRef {  public int add(int a, int b) {    return a+b;  }  public int sub(int a, int b) {    return a-b;  }  public int mul(int a, int b) {    return a*b;  }  public int div(int a, int b) {    return a/b;  }  public static void main(String[] args) {    try {      Integer[] input={new Integer(2),new Integer(6)};      Class cl=Class.forName("RunMthdRef"); // 這裡可能需要輸入類的全稱例如java.lang.String      Class[] par=new Class[2];      par[0]=Integer.TYPE;      par[1]=Integer.TYPE;      Method mthd=cl.getMethod("add",par);      Integer output=(Integer)mthd.invoke(new RunMthdRef(),input);      System.out.println(output.intValue());    } catch (Exception e) {      e.printStackTrace();    }   }} 

 

輸出: 8

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.