Java 反射入口及常见对象
相关jar包说明
java 相关源码在 JDK 包中可以看到
- rt.jar
- runtime
- java 基础类库
- dt.jar
- DesignTime
- 里面主要是 swing 相关的 BeanInfo 组件
- BeanInfo 可视化显示组件的配置相关
- tools.jar
- 工具类
- 包含 javac 相关
从类解析看反射
反射包:java.lang.reflect
1. Class类获取的反射对象
- Field 字段
- Method 方法
- Constructor 构造体
- Annotation 注解
- 这个不在反射包中
- java.lang.annotation
- getEnumConstants 获取枚举常量
- getXxx vs getDeclaredXxx
- getXxx 只会获取 public 的, 会获取父类的
- getDeclaredXxx 可以取得全部字段, 不会获取父类的
- getDeclaredXxx 可通过 getSuperclass().getDeclaredXxx() 获取父类的
// field
Field[] fields = User.class.getFields();
Field[] declaredFields = User.class.getDeclaredFields();
System.out.printf("1. fields: %s \n", Stream.of(fields).map(Field::getName).collect(Collectors.joining(",")));
System.out.printf("2. declaredFields: %s \n", Stream.of(declaredFields).map(Field::getName).collect(Collectors.joining(",")));
// method
Method[] methods = User.class.getMethods();
Method[] declaredMethods = User.class.getDeclaredMethods();
Method enclosingMethod = User.class.getEnclosingMethod();
Method enclosingMethod1 = new Object(){}.getClass().getEnclosingMethod();
System.out.println(enclosingMethod);
System.out.println(enclosingMethod1);
// constructor
Constructor<?>[] constructors = User.class.getConstructors();
Constructor<?>[] declaredConstructors = User.class.getDeclaredConstructors();
Constructor<?> enclosingConstructor = User.class.getEnclosingConstructor();
// annotation
Annotation[] annotations = User.class.getAnnotations();
Annotation[] declaredAnnotations = User.class.getDeclaredAnnotations();
// enum
Finger[] enumConstants = Finger.class.getEnumConstants();
System.out.printf("4. enumConstants: %s %s \n", enumConstants[0], enumConstants[1]);
2. Field 字段
- getFields and getDeclaredFields
- Member
- 标识 method\field\constructor 单个成员的反射信息
- Reflection
- 包:sun.reflect
- getCallerClass 获取调用对象的类
@CallerSensitive
public Field[] getFields() throws SecurityException {
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
return copyFields(privateGetPublicFields(null));
}
@CallerSensitive
public Field[] getDeclaredFields() throws SecurityException {
checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
return copyFields(privateGetDeclaredFields(false));
}
- Field
- AccessibleObject
- Field 继承了可访问对象 AccessibleObject
- FieldAccessor
- 字段访问器
- 包:sun.reflect
public final
class Field extends AccessibleObject implements Member {
// Cached field accessor created without override
private FieldAccessor fieldAccessor;
// Cached field accessor created with override
private FieldAccessor overrideFieldAccessor;
@CallerSensitive
public Object get(Object obj)
throws IllegalArgumentException, IllegalAccessException
{
if (!override) {
if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
Class<?> caller = Reflection.getCallerClass();
checkAccess(caller, clazz, obj, modifiers);
}
}
return getFieldAccessor(obj).get(obj);
}
// security check is done before calling this method
private FieldAccessor getFieldAccessor(Object obj)
throws IllegalAccessException
{
boolean ov = override;
FieldAccessor a = (ov) ? overrideFieldAccessor : fieldAccessor;
return (a != null) ? a : acquireFieldAccessor(ov);
}
@CallerSensitive
public void set(Object obj, Object value)
throws IllegalArgumentException, IllegalAccessException
{
if (!override) {
if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
Class<?> caller = Reflection.getCallerClass();
checkAccess(caller, clazz, obj, modifiers);
}
}
getFieldAccessor(obj).set(obj, value);
}
}
- AccessibleObject
- AnnotatedElement
- 带注释的元素
- 为 AccessibleObject 提供了获取注释的能力
public class AccessibleObject implements AnnotatedElement {
// 支持静态批量设置访问标识
public static void setAccessible(AccessibleObject[] array, boolean flag)
public void setAccessible(boolean flag)
public boolean isAccessible()
void checkAccess(Class<?> caller, Class<?> clazz, Object obj, int modifiers)
// Indicates whether language-level access checks are overridden
// by this object. Initializes to "false". This field is used by
// Field, Method, and Constructor.
//
// NOTE: for security purposes, this field must not be visible
// outside this package.
boolean override;
// ... ... AnnotatedElement method
}
- AnnotatedElement
- 提供获取注释的能力
public interface AnnotatedElement {
default boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
<T extends Annotation> T getAnnotation(Class<T> annotationClass);
Annotation[] getAnnotations();
default <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass)
default <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass)
default <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass)
Annotation[] getDeclaredAnnotations();
}
3. Method 方法
- getMethods and getDeclaredMethods and getEnclosingMethod
- getEnclosingMethod
- 获取匿名类或者内部类被外层使用的方法
@CallerSensitive
public Method[] getMethods() throws SecurityException {
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
return copyMethods(privateGetPublicMethods());
}
@CallerSensitive
public Method[] getDeclaredMethods() throws SecurityException {
checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
return copyMethods(privateGetDeclaredMethods(false));
}
@CallerSensitive
public Method getEnclosingMethod() throws SecurityException {
EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
if (enclosingInfo == null)
return null;
else {
// ... ...
}
}
- Method
- Executable
- 可执行的
public final class Method extends Executable {
private String name;
private Class<?> returnType;
private Class<?>[] parameterTypes;
private Class<?>[] exceptionTypes;
@CallerSensitive
public Object invoke(Object obj, Object... args)
throws IllegalAccessException, IllegalArgumentException,
InvocationTargetException
{
if (!override) {
if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
Class<?> caller = Reflection.getCallerClass();
checkAccess(caller, clazz, obj, modifiers);
}
}
MethodAccessor ma = methodAccessor; // read volatile
if (ma == null) {
ma = acquireMethodAccessor();
}
return ma.invoke(obj, args);
}
}
- Executable
- 提供可执行对象的相关方法
public abstract class Executable extends AccessibleObject
implements Member, GenericDeclaration {
public abstract String getName();
public Parameter[] getParameters() {
// TODO: This may eventually need to be guarded by security
// mechanisms similar to those in Field, Method, etc.
//
// Need to copy the cached array to prevent users from messing
// with it. Since parameters are immutable, we can
// shallow-copy.
return privateGetParameters().clone();
}
}
4. Constructor 构造体
- getConstructors and getDeclaredConstructors and getEnclosingConstructor
@CallerSensitive
public Constructor<?>[] getConstructors() throws SecurityException {
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
return copyConstructors(privateGetDeclaredConstructors(true));
}
@CallerSensitive
public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
return copyConstructors(privateGetDeclaredConstructors(false));
}
@CallerSensitive
public Constructor<?> getEnclosingConstructor() throws SecurityException {
// ... ...
}
- Constructor
public final class Constructor<T> extends Executable {
private Class<?>[] parameterTypes;
private Class<?>[] exceptionTypes;
}
@CallerSensitive
public T newInstance(Object ... initargs)
throws InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException
{
if (!override) {
if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
Class<?> caller = Reflection.getCallerClass();
checkAccess(caller, clazz, null, modifiers);
}
}
if ((clazz.getModifiers() & Modifier.ENUM) != 0)
throw new IllegalArgumentException("Cannot reflectively create enum objects");
ConstructorAccessor ca = constructorAccessor; // read volatile
if (ca == null) {
ca = acquireConstructorAccessor();
}
@SuppressWarnings("unchecked")
T inst = (T) ca.newInstance(initargs);
return inst;
}