1. 什么是反射?
反射(Reflection)能够让运行于JVM中的程序检测和修改运行时的行为。
2. 我们为何需要反射?
反射能够让我们:
- 在运行时检测对象的类型;
- 动态构造某个类的对象;
- 检测类的属性和方法;
- 任意调用对象的方法;
- 修改构造函数、方法、属性的可见性;
- 以及其他。
反射示例:Class.forName()
方法可以通过类或接口的名称(一个字符串或完全限定名)来获取对应的Class
对象。forName
方法会触发类的初始化。
// 使用反射
Class<?> c = Class.forName("classpath.and.classname");
Object dog = c.newInstance();
Method m = c.getDeclaredMethod("bark", new Class<?>[0]);
m.invoke(dog);
Class c = "foo".getClass();这返回的是String类型的class
enum E { A, B } Class c = A.getClass();A是枚举类型E的实例,所以返回的是E的Class
byte[] bytes = new byte[1024]; Class c = bytes.getClass();
(官方解释数组类型的getClass())Since arrays are Objects
, it is also possible to invoke getClass()
on an instance of an array. The returned Class
corresponds to an array with component type byte
.
Set<String> s = new HashSet<String>(); Class c = s.getClass();这里Set是一个接口,getClass()返回的是HashSet的class
The .class Syntax
boolean b; Class c = b.getClass(); // compile-time error Class c = boolean.class; // correct
TYPE Field for Primitive Type Wrappers
Class c = Double.TYPE;
Methods that Return Classes
-
返回指定类的super class
Class c = javax.swing.JButton.class.getSuperclass();
javax.swing.JButton
isjavax.swing.AbstractButton
.
Class.getSuperclass()
-
返回当前类的所有public classes, interfaces, and enums
- Returns all of the classes interfaces, and enums that are explicitly declared in this class.
Class.getClasses()
Class.getDeclaredClasses()
-
Returns the immediately enclosing class of the class.
Class c = Thread.State.class().getEnclosingClass();
Thread.State
isThread
.public class MyClass { static Object o = new Object() { public void m() {} }; static Class<c> = o.getClass().getEnclosingClass(); }
o
is enclosed byMyClass
.
Class.getEnclosingClass()