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();
   }
 
  }
}

苏生
803 声望725 粉丝