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

來源: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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章