测试类
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 修饰的只能用来反射公有的方法,其他如 AnnotationFieldConstructor 也是如此。
@SneakyThrows
public static void main(String[] args) {
// 类的完全限定名,不存在抛出classnotfound异常
Class> aClass = Class.forName("**.Student");
//使 用 newInstance 方 法 获 取 反 射 类 对 象
Object instance = aClass.newInstance();
System.out.println("==========fields==============");
// 获取对象中包含的所有字段
Field[] declaredFields = aClass.getDeclaredFields();
for (Field field : declaredFields) {
System.out.println(field);// Student.name,Student.age
}
System.out.println();
System.out.println("==========field==============");
// 获取需要使用的指定字段
Field age = aClass.getDeclaredField("age");
//age.setAccessible(true);
// 访问私有属性时需要加上以下
//Exception in thread "main" java.lang.IllegalAccessException: Class TestJava can not access a member of class Student with modifiers "private"
age.setAccessible(true);
// 设置参数属性
age.set(instance,"12");
System.out.println(age.get(instance));// 12
Method speak = aClass.getDeclaredMethod("speak");
// 私有方法需要加上以下
speak.setAccessible(true);
// 调用方法
speak.invoke(instance);
}



