1. 程式人生 > 實用技巧 >Java 反射機制 ( Java Reflection Mechanism )

Java 反射機制 ( Java Reflection Mechanism )

Example

@Data
public class Student {
  
    private int age;
}
public class Reflection {

    public static void main(String[] args) throws Exception {
      	// 正常呼叫
        Student student = new Student();
        student.setAge(18);
        System.out.println(student.getAge());

        // Reflection
        Class studentClass = Class.forName("com.git.Reflection.Student");
      
        // get method
        Method setAge = studentClass.getMethod("setAge", int.class);
        Method getAge = studentClass.getMethod("getAge");
      
      	// Constructor
        Constructor studentClassConstructor = studentClass.getConstructor();
      
      	// new 一個 Object
        Object o = studentClassConstructor.newInstance();
      
        setAge.invoke(o, 18);
      	Object age = getAge.invoke(o);
        System.out.println(age);
    }
}

執行結果完全是一樣的,區別就在,

第一段在程式碼未執行的時就已經確定了要執行的類(Student)

第二段程式碼則是在執行的時候通過類的全類名確定要執行的類 (Student)

反射就是在程式碼執行的時候才確定需要執行的類並且可以拿到其所有的方法

反射常用的 API

獲取反射中的Class物件
  • Class.forName 需要類的全類名

    Class studentClass = Class.forName("com.java.Reflection.Student");
    
  • Object.class

    Class<Student> studentClass = Student.class;
    
  • Object.getClass() 類物件的 getClass() 方法

    String s = new String("qqq");
    Class<? extends String> aClass1 = s.getClass();
    
通過反射建立物件
  • Class物件的 newInstance()方法
Class<Student> aClass = Student.class;
Student student = constructor.newInstance();
  • ConstructornewInstance()方法
Class<Student> studentClass = Student.class;
Constructor<Student> constructor = studentClass.getConstructor();
Student student = constructor.newInstance();
通過反射獲取類屬性、方法、構造器
  • 非私有屬性

    Class studentClass = Student.class;
    Field[] fields = studentClass.getFields();
    
    Constructor constructor = studentClass.getConstructor();
    System.out.println(constructor.toString());
    
    for (Field field : fields) {
    System.out.println(field.getName());
    }
    

    輸出結果

    public com.java.Reflection.Student()
    

    沒有輸出屬性,原因是 Student就沒有非私有的屬性,獲取私有的屬性需要用到關鍵字 declared

  • 全部屬性

Class studentClass = Student.class;
Field[] fields = studentClass.getDeclaredFields();

Constructor declaredConstructor = studentClass.getDeclaredConstructor();
System.out.println(declaredConstructor.toString());

for (Field field : fields) {
System.out.println(field.getName());
}

輸出結果

public com.ali.Reflection.Student()
age