public class Student {
private String name;
private String age;
public Student(){}
private void speak(){
System.out.println("I am free");
}
}
- 具体使用
- 注意点
通过 getFields()可以获取 Class 类的属性,但无法获取私有属性,而 getDeclaredFields()可 以获取到包括私有属性在内的所有属性。带有 Declared 修饰的方法可以反射到私有的方法, 没有 Declared 修饰的只能用来反射公有的方法,其他如 Annotation\Field\Constructor 也是如此。
@SneakyThrows
public static void main(String[] args) {
Class<?> aClass = Class.forName("**.Student");
Object instance = aClass.newInstance();
System.out.println("==========fields==============");
Field[] declaredFields = aClass.getDeclaredFields();
for (Field field : declaredFields) {
System.out.println(field);
}
System.out.println();
System.out.println("==========field==============");
Field age = aClass.getDeclaredField("age");
age.setAccessible(true);
age.set(instance,"12");
System.out.println(age.get(instance));
Method speak = aClass.getDeclaredMethod("speak");
speak.setAccessible(true);
speak.invoke(instance);
}