public class ReflectionDemo {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException,
InstantiationException, NoSuchMethodException, InvocationTargetException {
// 实例1:通过反射获取到Class元信息
Person person = new Person();
Class<? extends Person> aClass1 = person.getClass(); // 通过getClass获取元信息
Class<?> aClass2 = Class.forName("com.model.Person"); // 通过forName获取元信息
// 实例2:通过反射获取类名,包名
String name = aClass1.getName(); // 全路径类名 > cn.lazyfennec.model.Person
String simpleName = aClass1.getSimpleName(); // 不包含路径 > Person
Package aPackage = aClass1.getPackage(); // 包名 > package cn.lazyfennec.model
System.out.println(name);
System.out.println(simpleName);
System.out.println(aPackage);
System.out.println("===============================");
// 实例3:获取类属性
Field[] declaredFields = aClass1.getDeclaredFields();
for (Field declaredField : declaredFields) {
System.out.println(declaredField);
}
// 实例4:获取类属性的具体的值
person.setId(1);
person.setName("Neco");
for (Field declaredField : declaredFields) {
declaredField.setAccessible(true); // 设置属性可见可访问,处理私有属性无法访问的问题
System.out.println(declaredField.get(person));
}
// 实例4的另一种写法,只是简单的写法,可以进行优化
Object obj = aClass1.newInstance(); // 实例化一个新的对象, 相当于反射中的实例化
declaredFields = obj.getClass().getDeclaredFields();
for (Field declaredField : declaredFields) {
declaredField.setAccessible(true);
if (declaredField.getName().equals("name")) {
declaredField.set(obj, "Neco");
} else {
declaredField.set(obj, 1);
}
System.out.println(declaredField.get(obj));
}
// 实例5:反射获取当前类的方法
Method[] methods = aClass1.getMethods();
for (Method method : methods) {
System.out.println(method.getName());
}
Method method = aClass1.getMethod("getString");
Object invoke = method.invoke(obj);
System.out.println(invoke);
// 实例6:反射获得注解
Study study = aClass1.getAnnotation(Study.class); // 从类中获取注解
System.out.println(study);
String[] mores = study.mores();
String name1 = study.name();
System.out.println("name: " + name1 + " mores: " + mores);
// 从方法上获取注解
methods = aClass1.getDeclaredMethods();
for (Method method1 : methods) {
Study annotation = method1.getAnnotation(Study.class);
if (annotation == null) continue;
String name2 = annotation.name();
String[] mores1 = annotation.mores();
System.out.println("name: " + name2 + " mores: " + mores1);
}
// 从属性上获取注解
declaredFields = aClass1.getDeclaredFields();
for (Field declaredField : declaredFields) {
Study annotation = declaredField.getAnnotation(Study.class);
if (annotation == null) continue;
String annotationName = annotation.name();
String[] annotationMores = annotation.mores();
System.out.println("name: " + annotationName + " mores: " + annotationMores);
}
}
}