Java源码赏析(六)Class 类

Class 类是每一个程序员都必须了解的,也是使用反射机制的基础。

这篇文章将Class 类的公共方法大致介绍了一遍(省略了安全、枚举、断言、注解相关代码)。

代码 package java.lang; //省略 import /** * 类的实例:正在运行的Java应用中的类/接口 */ public final class Class<T> implements java.io.Serializable, GenericDeclaration, Type, AnnotatedElement { private static final int ANNOTATION= 0x00002000; private static final int ENUM = 0x00004000; private static final int SYNTHETIC = 0x00001000; private static native void registerNatives(); static { registerNatives(); } /* * 私有化构造方法,只有JVM才能创建Class对象 */ private Class(ClassLoader loader) { classLoader = loader; } /** * 根据类型生成字符串 "接口/类 名称" */ public String toString() { return (isInterface() ? "interface " : (isPrimitive() ? "" : "class ")) + getName(); } /** * 给出完整名称(包括类型,修饰符,参数等) * * @since 1.8 */ public String toGenericString() { ... } /** * 通过类的全限定名获取Class对象 */ @CallerSensitive public static Class<?> forName(String className) throws ClassNotFoundException { Class<?> caller = Reflection.getCallerClass(); return forName0(className, true, ClassLoader.getClassLoader(caller), caller); } /** * 调用类的无参构造方法创建对象 */ @CallerSensitive public T newInstance() throws InstantiationException, IllegalAccessException { ... } /** * 判断obj是否动态等效(dynamic equivalent)某个类的实例化对象 */ public native boolean isInstance(Object obj); /** * cls的参数和某个类是否一致,或是否为超类或超接口 */ public native boolean isAssignableFrom(Class<?> cls); /** * 本地方法判断是否为接口 */ public native boolean isInterface(); /** * 本地方法判断是否为数组 */ public native boolean isArray(); /** * 本地方法判断是否为基础数据类型 */ public native boolean isPrimitive(); /** * 判断是否为注解 */ public boolean isAnnotation() { return (getModifiers() & ANNOTATION) != 0; } /** * 判断是否为Java语言规范所定义的综合类 */ public boolean isSynthetic() { return (getModifiers() & SYNTHETIC) != 0; } /** * 获取类的名称 */ public String getName() { String name = this.name; if (name == null) this.name = name = getName0(); return name; } /** * 获取类加载器 */ @CallerSensitive public ClassLoader getClassLoader() { ClassLoader cl = getClassLoader0(); if (cl == null) return null; SecurityManager sm = System.getSecurityManager(); if (sm != null) { ClassLoader.checkClassLoaderPermission(cl, Reflection.getCallerClass()); } return cl; } /** * 获得类的类型参数 */ @SuppressWarnings("unchecked") public TypeVariable<Class<T>>[] getTypeParameters() { ClassRepository info = getGenericInfo(); if (info != null) return (TypeVariable<Class<T>>[])info.getTypeParameters(); else return (TypeVariable<Class<T>>[])new TypeVariable<?>[0]; } /** * 获得该类的父类 */ public native Class<? super T> getSuperclass(); /** * 获得该类的父类(包含泛型参数) * @since 1.5 */ public Type getGenericSuperclass() { ClassRepository info = getGenericInfo(); if (info == null) { return getSuperclass(); } if (isInterface()) { return null; } return info.getSuperclass(); } /** * 获得包 */ public Package getPackage() { return Package.getPackage(this); } /** * 获得实现的接口数组 */ public Class<?>[] getInterfaces() { ReflectionData<T> rd = reflectionData(); if (rd == null) { return getInterfaces0(); } else { Class<?>[] interfaces = rd.interfaces; if (interfaces == null) { interfaces = getInterfaces0(); rd.interfaces = interfaces; } return interfaces.clone(); } } /** * 获得实现的接口数组(带泛型) */ public Type[] getGenericInterfaces() { ClassRepository info = getGenericInfo(); return (info == null) ? getInterfaces() : info.getSuperInterfaces(); } /** * 获得数组的Class对象 */ public native Class<?> getComponentType(); /** * 获得类的修饰符 */ public native int getModifiers(); /** * 获得类的签名 */ public native Object[] getSigners(); /** * 设置类的签名 */ native void setSigners(Object[] signers); /** * 若该类是本地类或匿名类,则获取此类的方法 * @since 1.5 */ @CallerSensitive public Method getEnclosingMethod() throws SecurityException { ... } /** * 若该类是本地类或匿名类,则获取此类的构造方法 * @since 1.5 */ @CallerSensitive public Constructor<?> getEnclosingConstructor() throws SecurityException { ... } /** * 返回声明此方法的类 */ @CallerSensitive public Class<?> getDeclaringClass() throws SecurityException { final Class<?> candidate = getDeclaringClass0(); if (candidate != null) candidate.checkPackageAccess( ClassLoader.getClassLoader(Reflection.getCallerClass()), true); return candidate; } /** * 若该类是本地类或匿名类,则获取此类的外部类 * @since 1.5 */ @CallerSensitive public Class<?> getEnclosingClass() throws SecurityException { ... } /** * 获得一个简单类名 * @since 1.5 */ public String getSimpleName() { ... } /** * 获得该类类型的名称 * @since 1.8 */ public String getTypeName() { ... } /** * 获得Java语言规范定义的名称 * @since 1.5 */ public String getCanonicalName() { ... } /** * 判断是否为局部类 * @since 1.5 */ public boolean isLocalClass() { return isLocalOrAnonymousClass() && !isAnonymousClass(); } /** * 判断是否为成员类 * @since 1.5 */ public boolean isMemberClass() { return getSimpleBinaryName() != null && !isLocalOrAnonymousClass(); } /** * 获得类的全限定名称 */ private String getSimpleBinaryName() { Class<?> enclosingClass = getEnclosingClass(); if (enclosingClass == null) // top level class return null; try { return getName().substring(enclosingClass.getName().length()); } catch (IndexOutOfBoundsException ex) { throw new InternalError("Malformed class name", ex); } } /** * 获得类以及父类的所有的public的内部类 */ @CallerSensitive public Class<?>[] getClasses() { ... } /** * 获得类、父类的公共属性 */ @CallerSensitive public Field[] getFields() throws SecurityException { checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true); return copyFields(privateGetPublicFields(null)); } /** * 获得类、父类的公共方法 */ @CallerSensitive public Method[] getMethods() throws SecurityException { checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true); return copyMethods(privateGetPublicMethods()); } /** * 获取公共的构造函数 */ @CallerSensitive public Constructor<?>[] getConstructors() throws SecurityException { checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true); return copyConstructors(privateGetDeclaredConstructors(true)); } @CallerSensitive public Field getField(String name) throws NoSuchFieldException, SecurityException { checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true); Field field = getField0(name); if (field == null) { throw new NoSuchFieldException(name); } return field; } @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; } @CallerSensitive public Constructor<T> getConstructor(Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException { checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true); return getConstructor0(parameterTypes, Member.PUBLIC); } /** * 获得该类的所有内部类 */ @CallerSensitive public Class<?>[] getDeclaredClasses() throws SecurityException { checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), false); return getDeclaredClasses0(); } /** * 获得该类的所有属性 */ @CallerSensitive public Field[] getDeclaredFields() throws SecurityException { checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); return copyFields(privateGetDeclaredFields(false)); } /** * 获得该类的所有方法(不包括构造方法) */ @CallerSensitive public Method[] getDeclaredMethods() throws SecurityException { checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); return copyMethods(privateGetDeclaredMethods(false)); } /** * 获得该类的所有构造方法 */ @CallerSensitive public Constructor<?>[] getDeclaredConstructors() throws SecurityException { checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); return copyConstructors(privateGetDeclaredConstructors(false)); } @CallerSensitive public Field getDeclaredField(String name) throws NoSuchFieldException, SecurityException { checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); Field field = searchFields(privateGetDeclaredFields(false), name); if (field == null) { throw new NoSuchFieldException(name); } return field; } @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; } @CallerSensitive public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException { checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); return getConstructor0(parameterTypes, Member.DECLARED); } /** * 通过相对路径获取input流 */ public InputStream getResourceAsStream(String name) { name = resolveName(name); ClassLoader cl = getClassLoader0(); if (cl==null) { // A system class. return ClassLoader.getSystemResourceAsStream(name); } return cl.getResourceAsStream(name); } /** * 通过相对路径获取URL */ public java.net.URL getResource(String name) { name = resolveName(name); ClassLoader cl = getClassLoader0(); if (cl==null) { // A system class. return ClassLoader.getSystemResource(name); } return cl.getResource(name); } /** 下面数据Java安全相关内容,暂不考虑 */ /** * 获取类的ProtectionDomain(保护域) */ public java.security.ProtectionDomain getProtectionDomain() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(SecurityConstants.GET_PD_PERMISSION); } java.security.ProtectionDomain pd = getProtectionDomain0(); if (pd == null) { if (allPermDomain == null) { java.security.Permissions perms = new java.security.Permissions(); perms.add(SecurityConstants.ALL_PERMISSION); allPermDomain = new java.security.ProtectionDomain(null, perms); } pd = allPermDomain; } return pd; } /** * 移除了序列化相关代码 */ /** * 移除了枚举、断言部分代码 */ /** * 将obj强制转化类型 * * @since 1.5 */ @SuppressWarnings("unchecked") public T cast(Object obj) { if (obj != null && !isInstance(obj)) throw new ClassCastException(cannotCastMsg(obj)); return (T) obj; } /** * 将类转化为clazz的子类 * @since 1.5 */ @SuppressWarnings("unchecked") public <U> Class<? extends U> asSubclass(Class<U> clazz) { if (clazz.isAssignableFrom(this)) return (Class<? extends U>) this; else throw new ClassCastException(this.toString()); } /** * 移除注解部分代码 */ } 待续

下一篇Java源码赏析将会进行实例讲解

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwfyfp.html