超詳細的JVM反射原理技術點總結哦~

2020-10-10 18:01:40

欄目今天介紹超詳細的JVM反射原理技術點總結哦。

反射定義

1,JAVA反射機制是在執行狀態中

對於任意一個類,都能夠知道這個類的所有屬性和方法;

對於任意一個物件,都能夠呼叫它的任意一個方法和屬性;

這種動態獲取的資訊以及動態呼叫物件的方法的功能稱為java語言的反射機制。

反射提供的功能:

  • 在執行時判斷任意一個物件所屬的類
  • 在執行時構造任意一個類的物件
  • 在執行時判斷任意一個類所具有的成員變數和方法
  • 在執行時呼叫任意一個物件的方法

(如果屬性是private,正常情況下是不允許外界操作屬性值,這裡可以用Field類的setAccessible(true)方法,暫時開啟操作的許可權)

反射的使用場景

  • Java編碼時知道類和物件的具體資訊,此時直接對類和物件進行操作即可,無需反射
  • 如果編碼時不知道類或者物件的具體資訊,此時應該使用反射來實現

反射原始碼解析

舉例API :

Class.forName("com.my.reflectTest").newInstance()複製程式碼

1. 反射獲取類範例 Class.forName("xxx");

  首先呼叫了 java.lang.Class 的靜態方法,獲取類資訊!

注意:forName()反射獲取類資訊,並沒有將實現留給了java,而是交給了jvm去載入!

主要是先獲取 ClassLoader, 然後呼叫 native 方法,獲取資訊,載入類則是回撥 入參ClassLoader 進類載入!

 @CallerSensitive
    public static Class<?> forName(String className)
                throws ClassNotFoundException {
        // 先通過反射,獲取呼叫進來的類資訊,從而獲取當前的 classLoader
        Class<?> caller = Reflection.getCallerClass();
        // 呼叫native方法進行獲取class資訊
        return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
    }複製程式碼

2. java.lang.ClassLoader-----loadClass()

// java.lang.ClassLoader
    protected Class<?> loadClass(String name, boolean resolve)
        throws ClassNotFoundException
    {
        // 先獲取鎖
        synchronized (getClassLoadingLock(name)) {
            // First, check if the class has already been loaded
            // 如果已經載入了的話,就不用再載入了
            Class<?> c = findLoadedClass(name);
            if (c == null) {
                long t0 = System.nanoTime();
                try {
                    // 雙親委託載入
                    if (parent != null) {
                        c = parent.loadClass(name, false);
                    } else {
                        c = findBootstrapClassOrNull(name);
                    }
                } catch (ClassNotFoundException e) {
                    // ClassNotFoundException thrown if class not found
                    // from the non-null parent class loader
                }
 
                // 父類別沒有載入到時,再自己載入
                if (c == null) {
                    // If still not found, then invoke findClass in order
                    // to find the class.
                    long t1 = System.nanoTime();
                    c = findClass(name);
 
                    // this is the defining class loader; record the stats
                    sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
                    sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
                    sun.misc.PerfCounter.getFindClasses().increment();
                }
            }
            if (resolve) {
                resolveClass(c);
            }
            return c;
        }
    }
    
    protected Object getClassLoadingLock(String className) {
        Object lock = this;
        if (parallelLockMap != null) {
            // 使用 ConcurrentHashMap來儲存鎖
            Object newLock = new Object();
            lock = parallelLockMap.putIfAbsent(className, newLock);
            if (lock == null) {
                lock = newLock;
            }
        }
        return lock;
    }
    
    protected final Class<?> findLoadedClass(String name) {
        if (!checkName(name))
            return null;
        return findLoadedClass0(name);
    }複製程式碼

3. newInstance()

newInstance() 其實相當於呼叫類的無參建構函式,主要做了三件事複製程式碼
  • 許可權檢測,如果不通過直接丟擲異常;

  • 查詢無參構造器,並將其快取起來;

  • 呼叫具體方法的無參構造方法,生成範例並返回;

// 首先肯定是 Class.newInstance
    @CallerSensitive
    public T newInstance()
        throws InstantiationException, IllegalAccessException
    {
        if (System.getSecurityManager() != null) {
            checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);
        }
 
        // NOTE: the following code may not be strictly correct under
        // the current Java memory model.
 
        // Constructor lookup
        // newInstance() 其實相當於呼叫類的無參建構函式,所以,首先要找到其無參構造器
        if (cachedConstructor == null) {
            if (this == Class.class) {
                // 不允許呼叫 Class 的 newInstance() 方法
                throw new IllegalAccessException(
                    "Can not call newInstance() on the Class for java.lang.Class"
                );
            }
            try {
                // 獲取無參構造器
                Class<?>[] empty = {};
                final Constructor<T> c = getConstructor0(empty, Member.DECLARED);
                // Disable accessibility checks on the constructor
                // since we have to do the security check here anyway
                // (the stack depth is wrong for the Constructor's
                // security check to work)
                java.security.AccessController.doPrivileged(
                    new java.security.PrivilegedAction<Void>() {
                        public Void run() {
                                c.setAccessible(true);
                                return null;
                            }
                        });
                cachedConstructor = c;
            } catch (NoSuchMethodException e) {
                throw (InstantiationException)
                    new InstantiationException(getName()).initCause(e);
            }
        }
        Constructor<T> tmpConstructor = cachedConstructor;
        // Security check (same as in java.lang.reflect.Constructor)
        int modifiers = tmpConstructor.getModifiers();
        if (!Reflection.quickCheckMemberAccess(this, modifiers)) {
            Class<?> caller = Reflection.getCallerClass();
            if (newInstanceCallerCache != caller) {
                Reflection.ensureMemberAccess(caller, this, null, modifiers);
                newInstanceCallerCache = caller;
            }
        }
        // Run constructor
        try {
            // 呼叫無參構造器
            return tmpConstructor.newInstance((Object[])null);
        } catch (InvocationTargetException e) {
            Unsafe.getUnsafe().throwException(e.getTargetException());
            // Not reached
            return null;
        }
    }複製程式碼

4. getConstructor0() 為獲取匹配的構造方器;分三步:

  1. 先獲取所有的constructors, 然後通過進行引數型別比較;   2. 找到匹配後,通過 ReflectionFactory copy一份constructor返回;   3. 否則丟擲 NoSuchMethodException;

private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
                                        int which) throws NoSuchMethodException
    {
        // 獲取所有構造器
        Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
        for (Constructor<T> constructor : constructors) {
            if (arrayContentsEq(parameterTypes,
                                constructor.getParameterTypes())) {
                return getReflectionFactory().copyConstructor(constructor);
            }
        }
        throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes));
    }複製程式碼

5. privateGetDeclaredConstructors(), 獲取所有的構造器主要步驟;

  1. 先嚐試從快取中獲取;   2. 如果快取沒有,則從jvm中重新獲取,並存入快取,快取使用軟參照進行儲存,保證記憶體可用;

// 獲取當前類所有的構造方法,通過jvm或者快取
    // 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) {
        checkInitted();
        Constructor<T>[] res;
        // 呼叫 reflectionData(), 獲取儲存的資訊,使用軟參照儲存,從而使記憶體不夠可以回收
        ReflectionData<T> rd = reflectionData();
        if (rd != null) {
            res = publicOnly ? rd.publicConstructors : rd.declaredConstructors;
            // 存在快取,則直接返回
            if (res != null) return res;
        }
        // No cached value available; request value from VM
        if (isInterface()) {
            @SuppressWarnings("unchecked")
            Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0];
            res = temporaryRes;
        } else {
            // 使用native方法從jvm獲取構造器
            res = getDeclaredConstructors0(publicOnly);
        }
        if (rd != null) {
            // 最後,將從jvm中讀取的內容,存入快取
            if (publicOnly) {
                rd.publicConstructors = res;
            } else {
                rd.declaredConstructors = res;
            }
        }
        return res;
    }
    
    // Lazily create and cache ReflectionData
    private ReflectionData<T> reflectionData() {
        SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;
        int classRedefinedCount = this.classRedefinedCount;
        ReflectionData<T> rd;
        if (useCaches &&
            reflectionData != null &&
            (rd = reflectionData.get()) != null &&
            rd.redefinedCount == classRedefinedCount) {
            return rd;
        }
        // else no SoftReference or cleared SoftReference or stale ReflectionData
        // -> create and replace new instance
        return newReflectionData(reflectionData, classRedefinedCount);
    }
    
    // 新建立快取,儲存反射資訊
    private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData,
                                                int classRedefinedCount) {
        if (!useCaches) return null;
 
        // 使用cas保證更新的執行緒安全性,所以反射是保證執行緒安全的
        while (true) {
            ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount);
            // try to CAS it...
            if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) {
                return rd;
            }
            // 先使用CAS更新,如果更新成功,則立即返回,否則測查當前已被其他執行緒更新的情況,如果和自己想要更新的狀態一致,則也算是成功了
            oldReflectionData = this.reflectionData;
            classRedefinedCount = this.classRedefinedCount;
            if (oldReflectionData != null &&
                (rd = oldReflectionData.get()) != null &&
                rd.redefinedCount == classRedefinedCount) {
                return rd;
            }
        }
    }複製程式碼

另外,使用 relactionData() 進行快取儲存;ReflectionData 的資料結構如下!

// reflection data that might get invalidated when JVM TI RedefineClasses() is called
    private static class ReflectionData<T> {
        volatile Field[] declaredFields;
        volatile Field[] publicFields;
        volatile Method[] declaredMethods;
        volatile Method[] publicMethods;
        volatile Constructor<T>[] declaredConstructors;
        volatile Constructor<T>[] publicConstructors;
        // Intermediate results for getFields and getMethods
        volatile Field[] declaredPublicFields;
        volatile Method[] declaredPublicMethods;
        volatile Class<?>[] interfaces;
 
        // Value of classRedefinedCount when we created this ReflectionData instance
        final int redefinedCount;
 
        ReflectionData(int redefinedCount) {
            this.redefinedCount = redefinedCount;
        }
    }複製程式碼

6.通過上面,獲取到 Constructor 了!接下來就只需呼叫其相應構造器的 newInstance(),即返回範例了!

// return tmpConstructor.newInstance((Object[])null); 
    // java.lang.reflect.Constructor
    @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;
    }
    // sun.reflect.DelegatingConstructorAccessorImpl
    public Object newInstance(Object[] args)
      throws InstantiationException,
             IllegalArgumentException,
             InvocationTargetException
    {
        return delegate.newInstance(args);
    }
    // sun.reflect.NativeConstructorAccessorImpl
    public Object newInstance(Object[] args)
        throws InstantiationException,
               IllegalArgumentException,
               InvocationTargetException
    {
        // We can't inflate a constructor belonging to a vm-anonymous class
        // because that kind of class can't be referred to by name, hence can't
        // be found from the generated bytecode.
        if (++numInvocations > ReflectionFactory.inflationThreshold()
                && !ReflectUtil.isVMAnonymousClass(c.getDeclaringClass())) {
            ConstructorAccessorImpl acc = (ConstructorAccessorImpl)
                new MethodAccessorGenerator().
                    generateConstructor(c.getDeclaringClass(),
                                        c.getParameterTypes(),
                                        c.getExceptionTypes(),
                                        c.getModifiers());
            parent.setDelegate(acc);
        }
 
        // 呼叫native方法,進行呼叫 constructor
        return newInstance0(c, args);
    }複製程式碼

返回構造器的範例後,可以根據外部進行進行型別轉換,從而使用介面或方法進行呼叫範例功能了。

相關免費學習推薦:

以上就是超詳細的JVM反射原理技術點總結哦~的詳細內容,更多請關注TW511.COM其它相關文章!