反射(Reflection) 让程序能够在 运行时检查和操作类、方法和字段——甚至是那些在编译时未知的。注解(Annotations) 为代码附加元数据,工具和框架(通常借助反射)读取这些元数据来驱动行为。二者结合,支撑起了 Java 框架的大量"魔法"(Spring、JPA、JUnit)。
反射——运行时的检查与调用
java
Class<?> clazz = Class.forName();
(Field field : clazz.getDeclaredFields()) {
System.out.println(field.getName() + + field.getType());
}
(Method method : clazz.getDeclaredMethods()) {
System.out.println(method.getName());
}
clazz.getDeclaredConstructor().newInstance();
clazz.getMethod(, String.class);
m.invoke(instance, );
clazz.getDeclaredField();
f.setAccessible();
