1. 程式人生 > 實用技巧 >Java原始碼賞析(六)Class<T> 類

Java原始碼賞析(六)Class<T> 類

目的

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原始碼賞析將會進行例項講解