Class

  • 获取包信息
    /**
* 获取此对象所在的包
* @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);
}

最新文章

  1. iOS获取当前时间
  2. Swift 06.Closures
  3. 不使用ASP.NET中的服务器控件将如何上传文件?
  4. Docker的学习--介绍和安装
  5. 在VS2010中使用Outlook工具栏
  6. 修改ecshop让订单详情里将会员地址详情全部显示
  7. oracle 11g 分区表
  8. Web App中的Flexbox应用
  9. JavaScript OOP 思想
  10. Qt事件循环与状态机事件循环的思考
  11. 灵活使用getconf命令来获取系统信息
  12. [Swift]LeetCode322. 零钱兑换 | Coin Change
  13. docker 搭建 web 服务环境
  14. JSONObject基本内容(一)
  15. RabbitMq入门详解
  16. 设计模式之Memento(备忘机制)(转)
  17. python约束 异常 MD5 日志处理
  18. asp.net mvc session锁问题 (转载)
  19. mysql八:视图、触发器、事务、存储过程、函数
  20. Redis主从复制原理

热门文章

  1. centos redis自启动
  2. java指定运行jar包中的其中一个main方法
  3. functools:管理函数的工具
  4. JS笔记02
  5. windows消息的循环机制
  6. 更新对象sql语句
  7. 一键登录怎么在iOS端实现?这篇文章教会你!
  8. QOpenGLWidget
  9. Java常用类(二) Scanner类和大数类
  10. five rendering ideas 里获取csm的 shadow边界做 pcf