获取包信息
/**
* 获取此对象所在的包
* @revised 9
* @spec JPMS
*/
public Package getPackage() {
// 原始类型和数组无 Package
if (isPrimitive() || isArray()) {
return null;
}
final ClassLoader cl = getClassLoader0();
return cl != null ? cl.definePackage(this)
: BootLoader.definePackage(this);
}
/**
* 返回此类的全限定包名
*
* @since 9
* @spec JPMS
* @jls 6.7 Fully Qualified Names
*/
public String getPackageName() {
String pn = this.packageName;
if (pn == null) {
Class<?> c = this;
// 1)获取数组的最底层组件类型
while (c.isArray()) {
c = c.getComponentType();
}
// 2)如果是原始类型
if (c.isPrimitive()) {
pn = "java.lang";
} else {
// 3)获取组件名称
final String cn = c.getName();
// 尝试截取包名称
final int dot = cn.lastIndexOf('.');
pn = dot != -1 ? cn.substring(0, dot).intern() : "";
}
// 缓存包名称
this.packageName = pn;
}
return pn;
}
获取父类
/**
* 读取此类型的父类 Class
*/
@HotSpotIntrinsicCandidate
public native Class<? super T> getSuperclass();
获取所实现的接口
/**
* 0)按声明顺序返回此类直接实现的所有接口
* 1)未直接实现任何接口,则返回长度为 0 的数组
* 2)原始类型返回长度为 0 的数组
* 3)数组返回 Cloneable 和 Serializable 组成的数组
*/
public Class<?>[] getInterfaces() {
// defensively copy before handing over to user code
return getInterfaces(true);
}
private Class<?>[] getInterfaces(boolean cloneArray) {
final ReflectionData<T> rd = reflectionData();
if (rd == null) {
// no cloning required
return getInterfaces0();
} else {
// 尝试从缓存中读取
Class<?>[] interfaces = rd.interfaces;
if (interfaces == null) {
interfaces = getInterfaces0();
rd.interfaces = interfaces;
}
// defensively copy if requested
return cloneArray ? interfaces.clone() : interfaces;
}
}
private native Class<?>[] getInterfaces0();
读取成员类及接口
/**
* 返回此类及其父类中定义的所有 public 成员类和接口。
* 未定义成员类和接口、原始数据类型、数组都返回长度为 0 的 Class[]。
* @since 1.1
*/
@CallerSensitive
public Class<?>[] getClasses() {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), false);
}return java.security.AccessController.doPrivileged(
(PrivilegedAction<Class<?>[]>) () -> {
final List<Class<?>> list = new ArrayList<>();
Class<?> currentClass = Class.this;
while (currentClass != null) {
// 获取当前类中定义的所有 public 成员类和接口
for (final Class<?> m : currentClass.getDeclaredClasses()) {
if (Modifier.isPublic(m.getModifiers())) {
list.add(m);
}
}
// 递归处理其父类
currentClass = currentClass.getSuperclass();
}
return list.toArray(new Class<?>[0]);
});
}
/**
* 读取当前类中定义的所有成员类和接口
* @since 1.1
*/
@CallerSensitive
public Class<?>[] getDeclaredClasses() throws SecurityException {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), false);
}
return getDeclaredClasses0();
}
private native Class<?>[] getDeclaredClasses0();
读取构造函数
/**
* 读取此类中定义的所有 public 构造函数
* @since 1.1
*/
@CallerSensitive
public Constructor<?>[] getConstructors() throws SecurityException {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
}
return copyConstructors(privateGetDeclaredConstructors(true));
}
private static ReflectionFactory getReflectionFactory() {
if (reflectionFactory == null) {
reflectionFactory =
java.security.AccessController.doPrivileged
(new ReflectionFactory.GetReflectionFactoryAction());
}
return reflectionFactory;
}
// Returns an array of "root" constructors. These Constructor
// objects must NOT be propagated to the outside world, but must
// instead be copied via ReflectionFactory.copyConstructor.
private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {
Constructor<T>[] res;
final ReflectionData<T> rd = reflectionData();
if (rd != null) {
// 只读取 public 构造函数还是所有声明的构造函数
res = publicOnly ? rd.publicConstructors : rd.declaredConstructors;
if (res != null) {
return res;
}
}
// No cached value available; request value from VM
// 1)如果是接口
if (isInterface()) {
res = (Constructor<T>[]) new Constructor<?>[0];
} else {
res = getDeclaredConstructors0(publicOnly);
}
if (rd != null) {
if (publicOnly) {
rd.publicConstructors = res;
} else {
rd.declaredConstructors = res;
}
}
return res;
}
private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
/**
* 读取带有指定类型参数列表的 public 构造函数
* @param parameterTypes 参数类型列表
* @since 1.1
*/
@CallerSensitive
public Constructor<T> getConstructor(Class<?>... parameterTypes)
throws NoSuchMethodException, SecurityException
{
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
}
return getReflectionFactory().copyConstructor(
getConstructor0(parameterTypes, Member.PUBLIC));
}
/**
* 读取指定带有指定参数类型列表的构造函数
*
* @param parameterTypes 参数类型列表
* @param which
*/
private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
int which) throws NoSuchMethodException
{
final ReflectionFactory fact = getReflectionFactory();
// 读取所有 public 构造函数
final Constructor<T>[] constructors = privateGetDeclaredConstructors(which == Member.PUBLIC);
for (final Constructor<T> constructor : constructors) {
// 数组内容相同
if (arrayContentsEq(parameterTypes,
fact.getExecutableSharedParameterTypes(constructor))) {
return constructor;
}
}
throw new NoSuchMethodException(methodToString("<init>", parameterTypes));
}
private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
if (a1 == null) {
return a2 == null || a2.length == 0;
}if (a2 == null) {
return a1.length == 0;
}
if (a1.length != a2.length) {
return false;
}
for (int i = 0; i < a1.length; i++) {
if (a1[i] != a2[i]) {
return false;
}
}
return true;
}
/**
* 读取此类中定义的所有构造函数
* @since 1.1
*/
@CallerSensitive
public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
}
return copyConstructors(privateGetDeclaredConstructors(false));
}
private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
final Constructor<U>[] out = arg.clone();
final ReflectionFactory fact = getReflectionFactory();
for (int i = 0; i < out.length; i++) {
out[i] = fact.copyConstructor(out[i]);
}
return out;
}
/**
* 读取带有指定类型参数列表的 public 构造函数
*
* @return 指定类型的参数列表
* @since 1.1
*/
@CallerSensitive
public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
throws NoSuchMethodException, SecurityException
{
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
}return getReflectionFactory().copyConstructor(
getConstructor0(parameterTypes, Member.DECLARED));
}
读取方法
/**
* 读取此类中定义的所有 public 方法,包括递归从父类和父接口中继承的 public 方法
* @since 1.1
*/
@CallerSensitive
public Method[] getMethods() throws SecurityException {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
}
return copyMethods(privateGetPublicMethods());
}
// Returns an array of "root" methods. These Method objects must NOT
// be propagated to the outside world, but must instead be copied
// via ReflectionFactory.copyMethod.
private Method[] privateGetPublicMethods() {
Method[] res;
// 1)尝试从缓存中读取
final ReflectionData<T> rd = reflectionData();
if (rd != null) {
res = rd.publicMethods;
if (res != null) {
return res;
}
}// 2)无缓存,读取此类中声明的所有 public 方法
final PublicMethods pms = new PublicMethods();
for (final Method m : privateGetDeclaredMethods(/* publicOnly */ true)) {
pms.merge(m);
}
// 3)递归处理父类中的 public 方法
final Class<?> sc = getSuperclass();
if (sc != null) {
for (final Method m : sc.privateGetPublicMethods()) {
pms.merge(m);
}
}
// 4)递归处理父接口
for (final Class<?> intf : getInterfaces(/* cloneArray */ false)) {
for (final Method m : intf.privateGetPublicMethods()) {
// static interface methods are not inherited
if (!Modifier.isStatic(m.getModifiers())) {
pms.merge(m);
}
}
}
res = pms.toArray();
// 如果启用了缓存则写入
if (rd != null) {
rd.publicMethods = res;
}
return res;
}
private static Method[] copyMethods(Method[] arg) {
final Method[] out = new Method[arg.length];
final ReflectionFactory fact = getReflectionFactory();
for (int i = 0; i < arg.length; i++) {
out[i] = fact.copyMethod(arg[i]);
}
return out;
}
/**
* 读取名称为 name,并带有指定参数列表的方法
*
* @param name 方法的名称
* @param parameterTypes 参数类型列表
* @since 1.1
*/
@CallerSensitive
public Method getMethod(String name, Class<?>... parameterTypes)
throws NoSuchMethodException, SecurityException {
Objects.requireNonNull(name);
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
}
final Method method = getMethod0(name, parameterTypes);
if (method == null) {
throw new NoSuchMethodException(methodToString(name, parameterTypes));
}
return getReflectionFactory().copyMethod(method);
}
// Returns a "root" Method object. This Method object must NOT
// be propagated to the outside world, but must instead be copied
// via ReflectionFactory.copyMethod.
private Method getMethod0(String name, Class<?>[] parameterTypes) {
final PublicMethods.MethodList res = getMethodsRecursive(
name,
parameterTypes == null ? EMPTY_CLASS_ARRAY : parameterTypes,
/* includeStatic */ true);
return res == null ? null : res.getMostSpecific();
}
// Returns a list of "root" Method objects. These Method objects must NOT
// be propagated to the outside world, but must instead be copied
// via ReflectionFactory.copyMethod.
private PublicMethods.MethodList getMethodsRecursive(String name,
Class<?>[] parameterTypes,
boolean includeStatic) {
// 1)读取所有声明的 public 方法
final Method[] methods = privateGetDeclaredMethods(/* publicOnly */ true);
PublicMethods.MethodList res = PublicMethods.MethodList
.filter(methods, name, parameterTypes, includeStatic);
// 找到匹配方法,则直接返回
if (res != null) {
return res;
}// 递归从父类中查找
final Class<?> sc = getSuperclass();
if (sc != null) {
res = sc.getMethodsRecursive(name, parameterTypes, includeStatic);
}
// 递归从接口中查找
for (final Class<?> intf : getInterfaces(/* cloneArray */ false)) {
res = PublicMethods.MethodList.merge(
res, intf.getMethodsRecursive(name, parameterTypes,
/* includeStatic */ false));
}
return res;
}
/**
* 读取此类中定义的所有方法
* @since 1.1
*/
@CallerSensitive
public Method[] getDeclaredMethods() throws SecurityException {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
}
return copyMethods(privateGetDeclaredMethods(false));
}
// Returns an array of "root" methods. These Method objects must NOT
// be propagated to the outside world, but must instead be copied
// via ReflectionFactory.copyMethod.
private Method[] privateGetDeclaredMethods(boolean publicOnly) {
Method[] res;
// 1)尝试从缓存中读取
final ReflectionData<T> rd = reflectionData();
if (rd != null) {
res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;
if (res != null) {
return res;
}
}
// 从 VM 中查找结果
res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
// 如果存在缓存,则写入
if (rd != null) {
if (publicOnly) {
rd.declaredPublicMethods = res;
} else {
rd.declaredMethods = res;
}
}
return res;
}
/**
* 读取此类中名称为 name 并且具有指定类型参数列表的方法
*
* @param name 方法的名称
* @param parameterTypes 参数类型列表
* @since 1.1
*/
@CallerSensitive
public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
throws NoSuchMethodException, SecurityException {
Objects.requireNonNull(name);
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
}
final Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
if (method == null) {
throw new NoSuchMethodException(methodToString(name, parameterTypes));
}
return getReflectionFactory().copyMethod(method);
}
// This method does not copy the returned Method object!
private static Method searchMethods(Method[] methods,
String name,
Class<?>[] parameterTypes)
{
final ReflectionFactory fact = getReflectionFactory();
Method res = null;
for (final Method m : methods) {
// 方法名称一致 && 参数类型列表一致 && 返回值类型兼容
if (m.getName().equals(name)
&& arrayContentsEq(parameterTypes,
fact.getExecutableSharedParameterTypes(m))
&& (res == null
|| res.getReturnType() != m.getReturnType()
&& res.getReturnType().isAssignableFrom(m.getReturnType()))) {
res = m;
}
}
return res;
}
读取属性
/**
* 返回此类及其递归父类和接口中定义的所有 public 字段
*/
@CallerSensitive
public Field[] getFields() throws SecurityException {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
}
return copyFields(privateGetPublicFields());
}
private static Field[] copyFields(Field[] arg) {
final Field[] out = new Field[arg.length];
final ReflectionFactory fact = getReflectionFactory();
for (int i = 0; i < arg.length; i++) {
out[i] = fact.copyField(arg[i]);
}
return out;
}
// Returns an array of "root" fields. These Field objects must NOT
// be propagated to the outside world, but must instead be copied
// via ReflectionFactory.copyField.
private Field[] privateGetPublicFields() {
Field[] res;
// 尝试从缓存中读取
final ReflectionData<T> rd = reflectionData();
if (rd != null) {
res = rd.publicFields;
if (res != null) {
return res;
}
}final LinkedHashSet<Field> fields = new LinkedHashSet<>();
// 此类中定义的 public 属性
addAll(fields, privateGetDeclaredFields(true));
// 递归的接口中
for (final Class<?> si : getInterfaces()) {
addAll(fields, si.privateGetPublicFields());
}
// 递归的父类中
final Class<?> sc = getSuperclass();
if (sc != null) {
addAll(fields, sc.privateGetPublicFields());
}
res = fields.toArray(new Field[0]);
if (rd != null) {
rd.publicFields = res;
}
return res;
}
// Returns an array of "root" fields. These Field objects must NOT
// be propagated to the outside world, but must instead be copied
// via ReflectionFactory.copyField.
private Field[] privateGetDeclaredFields(boolean publicOnly) {
Field[] res;
// 尝试从缓存中读取
final ReflectionData<T> rd = reflectionData();
if (rd != null) {
res = publicOnly ? rd.declaredPublicFields : rd.declaredFields;
if (res != null) {
return res;
}
}
// 从 JVM 中读取
res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
if (rd != null) {
if (publicOnly) {
rd.declaredPublicFields = res;
} else {
rd.declaredFields = res;
}
}
return res;
}
private native Field[] getDeclaredFields0(boolean publicOnly);
/**
* 读取指定名称的 public 字段
* @param name 字段名称
* @since 1.1
*/
@CallerSensitive
public Field getField(String name)
throws NoSuchFieldException, SecurityException {
Objects.requireNonNull(name);
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
}
final Field field = getField0(name);
if (field == null) {
throw new NoSuchFieldException(name);
}
return getReflectionFactory().copyField(field);
}
// Returns a "root" Field object. This Field object must NOT
// be propagated to the outside world, but must instead be copied
// via ReflectionFactory.copyField.
private Field getField0(String name) {
// Note: the intent is that the search algorithm this routine
// uses be equivalent to the ordering imposed by
// privateGetPublicFields(). It fetches only the declared
// public fields for each class, however, to reduce the number
// of Field objects which have to be created for the common
// case where the field being requested is declared in the
// class which is being queried.
Field res;
// Search declared public fields
if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
return res;
}
// Direct superinterfaces, recursively
final Class<?>[] interfaces = getInterfaces(/* cloneArray */ false);
for (final Class<?> c : interfaces) {
if ((res = c.getField0(name)) != null) {
return res;
}
}
// Direct superclass, recursively
if (!isInterface()) {
final Class<?> c = getSuperclass();
if (c != null) {
if ((res = c.getField0(name)) != null) {
return res;
}
}
}
return null;
}
// This method does not copy the returned Field object!
private static Field searchFields(Field[] fields, String name) {
for (final Field field : fields) {
// 当前字段的名称和 name 相等
if (field.getName().equals(name)) {
return field;
}
}
return null;
}
/**
* 读取此类中直接定义的所有字段
* @since 1.1
*/
@CallerSensitive
public Field[] getDeclaredFields() throws SecurityException {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
}
return copyFields(privateGetDeclaredFields(false));
}
private static Field[] copyFields(Field[] arg) {
final Field[] out = new Field[arg.length];
final ReflectionFactory fact = getReflectionFactory();
for (int i = 0; i < arg.length; i++) {
out[i] = fact.copyField(arg[i]);
}
return out;
}
/**
* 读取此类中指定名称的字段
*
* @param name 字段名称
* @since 1.1
*/
@CallerSensitive
public Field getDeclaredField(String name)
throws NoSuchFieldException, SecurityException {
Objects.requireNonNull(name);
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
}
final Field field = searchFields(privateGetDeclaredFields(false), name);
if (field == null) {
throw new NoSuchFieldException(name);
}
return getReflectionFactory().copyField(field);
}
读取注解
/**
* 读取此类上保留策略为 RetentionPolicy.RUNTIME 的所有直接注解,
* 递归读取父类中保留策略为 RetentionPolicy.RUNTIME 并且带有 @Inherited 的所有注解
* 顶层父类的注解优先读取。
* @since 1.5
*/
@Override
public Annotation[] getAnnotations() {
return AnnotationParser.toArray(annotationData().annotations);
}
/**
* 读取指定类型的注解
*/
@SuppressWarnings("unchecked")
public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
Objects.requireNonNull(annotationClass);return (A) annotationData().annotations.get(annotationClass);
}
/**
* 读取此类上保留策略为 RetentionPolicy.RUNTIME 的所有直接注解
*/
@Override
public Annotation[] getDeclaredAnnotations() {
return AnnotationParser.toArray(annotationData().declaredAnnotations);
}
/**
* 读取此类上保留策略为 RetentionPolicy.RUNTIME 的指定类型的注解
* @since 1.8
*/
@Override
@SuppressWarnings("unchecked")
public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) {
Objects.requireNonNull(annotationClass);return (A) annotationData().declaredAnnotations.get(annotationClass);
}
/**
* 获取此类直接的或间接的指定类型的所有注解
* @since 1.8
*/
@Override
public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass) {
Objects.requireNonNull(annotationClass);
return AnnotationSupport.getDirectlyAndIndirectlyPresent(annotationData().declaredAnnotations,
annotationClass);
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章