Java知識點總結(反射-經過反射操做類的屬性和方法 )

Java知識點總結(反射-經過反射操做類的屬性和方法 )

@(Java知識點總結)[Java, 反射]java

使用反射操做類的屬性和方法:安全

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
 
public class Test03 {
 
  // 經過反射API調用構造方法,構造對象
  public static void getInstance(Class clazz){
 
   Student student;
   try {
     student = (Student) clazz.newInstance();  // 其實調用無參構造器
     student.setName("張三");
     System.out.println(student.getName());
   } catch (InstantiationException | IllegalAccessException e) {
     e.printStackTrace();
   }
   
   try {
     Constructor c = clazz.getDeclaredConstructor(int.class, String.class);// 調用有參構造器
     Student student2 = (Student) c.newInstance(1, "李四");
     System.out.println(student2.getName());
   } catch (NoSuchMethodException | SecurityException | InstantiationException |
      IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
     e.printStackTrace();
   }
 
  }
 
  // 經過反射API調用普通方法
  public static void method(Class clazz)  {
   try {
     Student student = (Student) clazz.newInstance();
     // 獲取方法
     Method method = clazz.getDeclaredMethod("setName", String.class);
     // 激活方法
     method.invoke(student, "王武");  // student.setName("王武");
     System.out.println(student.getName());
   } catch (InstantiationException | IllegalAccessException
      | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException e) {
     e.printStackTrace();
   }
  }
 
  //經過反射API操做屬性
  public static void field(Class clazz){
   try {
     Student student = (Student) clazz.newInstance();
     Field f1 = clazz.getDeclaredField("name");
     
     // name 是private屬性,若是不寫會:IllegalAccessException
     f1.setAccessible(true); // 這個私有屬性不用作安全檢查了,能夠直接訪問
     f1.set(student, "趙六");
     
     Field f2 = clazz.getDeclaredField("sex"); // sex 是public 屬性,不用忽略安全檢查
     f2.set(student, "男");
     
     for (Field f : clazz.getDeclaredFields()) {
      f.setAccessible(true);
      System.out.println(f.get(student)); //注意參數是對象名,而不是屬性名
     }
     
   } catch (NoSuchFieldException | SecurityException |
      IllegalArgumentException | IllegalAccessException | InstantiationException e) {
     e.printStackTrace();
   }
  }
  public static void main(String[] args) {
   String path = "com.gs.Student";
   try {
     Class clazz = Class.forName(path);
     //getInstance(clazz);
     //method(clazz);
     field(clazz);
   } catch (Exception e) {
     e.printStackTrace();
   }
 
  }
}
相關文章
相關標籤/搜索