1 获取并调用方法

  1. 通过Class.getDeclaredMethod(name, argType1, argType2, ...)获取方法method
  2. 通过method.invoke(obj, arg1, arg2, ...)调用方法

    1. public class TestReflection {
    2. public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
    3. Class clazz = Class.forName("com.lht.reflection.User");
    4. Constructor constructor = clazz.getDeclaredConstructor(String.class, int.class);
    5. User user = (User) constructor.newInstance("lirt", 210224);
    6. System.out.println(user);
    7. Method setName = clazz.getDeclaredMethod("setName", String.class);
    8. setName.invoke(user, "new name");
    9. System.out.println(user);
    10. }
    11. }

2 操作属性

  1. 通过Class.getDeclaredField(name)获取属性field
  2. 通过field.set(obj, newField)设置属性值

    1. public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
    2. Class clazz = Class.forName("com.lht.reflection.User");
    3. Constructor constructor = clazz.getDeclaredConstructor(String.class, int.class);
    4. User user = (User) constructor.newInstance("lirt", 210224);
    5. System.out.println(user);
    6. Field name = clazz.getDeclaredField("name");
    7. name.set(user, "hahaha");
    8. System.out.println(user);
    9. }

    但执行上述代码会报错,因为user.name属性是 private 的,不能直接访问。 如果想访问这个属性,就需要加入一行代码name.setAccessible(true);来关闭安全检测。 同理,如果先访问私有方法,也需要method.setAccessible(true);

image.png