反射机制

JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意方法和属性;这种动态获取信息以及动态调用对象方法的功能称为java语言的反射机制。

用途

在日常的第三方应用开发过程中,经常会遇到某个类的某个成员变量、方法或是属性是私有的或是只对系统应用开放,这时候就可以利用Java的反射机制通过反射来获取所需的私有成员或是方法。

反射机制的相关类

类名 用途
Class类 代表类的实体,在运行的Java应用程序中表示类和接口
Field类 代表类的成员变量(成员变量也称为类的属性)
Method类 代表类的方法
Constructor类 代表类的构造方法

Class类

Class代表类的实体,在运行的Java应用程序中表示类和接口。在这个类中提供了很多有用的方法,这里对他们简单的分类介绍。

获得类相关的方法

方法 用途
asSubclass(Class clazz) 把传递的类的对象转换成代表其子类的对象
Cast 把对象转换成代表类或是接口的对象
getClassLoader() 获得类的加载器
getClasses() 返回一个数组,数组中包含此类以及父类中所有公共类和接口类的对象
getDeclaredClasses() 返回一个数组,数组中包含此类中所有权限的所有类和接口类的对象
forName(String className) 根据类名返回类的对象
getName() 获得类的完整路径名字
newInstance() 创建类的实例
getPackage() 获得类的包
getSimpleName() 获得类的名字
getSuperclass() 获得当前类继承的父类的名字
getInterfaces() 获得当前类实现的类或是接口

获得类中属性相关的方法

方法 用途
getField(String name) 获得此类以及父类的公有的属性对象
getFields() 获得此类的以及父类的所有公有的属性对象
getDeclaredField(String name) 获得此类任何权限的属性对象
getDeclaredFields() 获得此类任何权限的所有属性对象

获得类中注解相关的方法

方法 用途
getAnnotation(Class annotationClass) 返回此类以及父类的与参数类型匹配的公有注解对象
getAnnotations() 返回此类以及父类的所有的公有注解对象
getDeclaredAnnotation(Class annotationClass) 返回此类任何权限中与参数类型匹配的所有注解对象
getDeclaredAnnotations() 返回此类任何权限所有的注解对象

获得类中构造器相关的方法

方法 用途
getConstructor(Class…<?> parameterTypes) 获得此类以及父类中与参数类型匹配的公有构造方法
getConstructors() 获得此类以及父类的所有公有构造方法
getDeclaredConstructor(Class…<?> parameterTypes) 获得此类任何权限中与参数类型匹配的构造方法
getDeclaredConstructors() 获得此类任何权限所有构造方法

获得类中方法相关的方法

方法 用途
getMethod(String name, Class…<?> parameterTypes) 获得此类以及父类该类某个公有的方法
getMethods() 获得此类以及父类所有公有的方法
getDeclaredMethod(String name, Class…<?> parameterTypes) 获得此类任何权限某个方法
getDeclaredMethods() 获得此类任何权限所有方法

getMethod和getDeclaredMethod源码

1
2
3
4
5
6
7
8
9
10
11
12
@CallerSensitive
public Method getMethod(String name, Class<?>... parameterTypes)
throws NoSuchMethodException, SecurityException {
//检测权限
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
//获取方法对象
Method method = getMethod0(name, parameterTypes, true);
if (method == null) {
throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
}
return method;
}
1
2
3
4
5
6
7
8
9
10
11
12
@CallerSensitive
public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
throws NoSuchMethodException, SecurityException {
//检测权限
checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
//获取方法对象
Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
if (method == null) {
throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
}
return method;
}

检查权限时,方法是一样的,只是检查范围不一样。

1
2
3
4
5
6
7
8
9
10
11
12
13
public interface Member {
/**
* Identifies the set of all public members of a class or interface,
* including inherited members.
*/
public static final int PUBLIC = 0;

/**
* Identifies the set of declared members of a class or interface.
* Inherited members are not included.
*/
public static final int DECLARED = 1;
}

即PUBLIC会包含所有的public方法,包括父类的方法。DECLARED会包括所有自己定义的方法,public、protected、default、private都在此,不包括父类的方法。

1
2
3
4
5
6
7
8
9
10
private Method getMethod0(String name, Class<?>[] parameterTypes, boolean includeStaticMethods) {
MethodArray interfaceCandidates = new MethodArray(2);
Method res = privateGetMethodRecursive(name, parameterTypes, includeStaticMethods, interfaceCandidates);
if (res != null)
return res;

// Not found on class or superclass directly
interfaceCandidates.removeLessSpecifics();
return interfaceCandidates.getFirst(); // may be null
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
private Method privateGetMethodRecursive(String name,
Class<?>[] parameterTypes,
boolean includeStaticMethods,
MethodArray allInterfaceCandidates) {
// Note: the intent is that the search algorithm this routine
// uses be equivalent to the ordering imposed by
// privateGetPublicMethods(). It fetches only the declared
// public methods for each class, however, to reduce the
// number of Method objects which have to be created for the
// common case where the method being requested is declared in
// the class which is being queried.
//
// Due to default methods, unless a method is found on a superclass,
// methods declared in any superinterface needs to be considered.
// Collect all candidates declared in superinterfaces in {@code
// allInterfaceCandidates} and select the most specific if no match on
// a superclass is found.

// Must _not_ return root methods
Method res;
// Search declared public methods
if ((res = searchMethods(privateGetDeclaredMethods(true),
name,
parameterTypes)) != null) {
if (includeStaticMethods || !Modifier.isStatic(res.getModifiers()))
return res;
}
// Search superclass's methods
if (!isInterface()) {
Class<? super T> c = getSuperclass();
if (c != null) {
if ((res = c.getMethod0(name, parameterTypes, true)) != null) {
return res;
}
}
}
// Search superinterfaces' methods
Class<?>[] interfaces = getInterfaces();
for (Class<?> c : interfaces)
if ((res = c.getMethod0(name, parameterTypes, false)) != null)
allInterfaceCandidates.add(res);
// Not found
return null;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private Method[] privateGetDeclaredMethods(boolean publicOnly) {
checkInitted();
Method[] res;
ReflectionData<T> rd = reflectionData();
if (rd != null) {
res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;
if (res != null) return res;
}
// No cached value available; request value from VM
res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
if (rd != null) {
if (publicOnly) {
rd.declaredPublicMethods = res;
} else {
rd.declaredMethods = res;
}
}
return res;
}

获取方法不同,getMethod调用 getMethod0,getDeclaredMethod调用privateGetDeclaredMethods。
getMethod0会递归查找父类方法,其中会调用到privateGetDeclaredMethods方法。

类中其他重要的方法

方法 用途
isAnnotation() 如果是注解类型则返回true
isAnnotationPresent(Class<? extends Annotation> annotationClass) 如果是指定类型注解类型则返回true
isAnonymousClass() 如果是匿名类则返回true
isArray() 如果是一个数组类则返回true
isEnum() 如果是枚举类则返回true
isInstance(Object obj) 如果obj是该类的实例则返回true
isInterface() 如果是接口类则返回true
isLocalClass() 如果是局部类则返回true
isMemberClass() 如果是内部类则返回true

Field类

Field代表类的成员变量(成员变量也称为类的属性)。

方法 用途
equals(Object obj) 属性与obj相等则返回true
get(Object obj) 获得obj中对应的属性值
set(Object obj, Object value) 设置obj中对应属性值

Method类

Method代表类的方法。

方法 用途
invoke(Object obj, Object… args) 传递object对象及参数调用该对象对应的方法

Constructor类

Constructor代表类的构造方法。

方法 用途
newInstance(Object… initargs) 根据传递的参数创建类的对象

获取私有方法或者属性时,需要设置setAccessible(true),取消Java语言访问检查。