java之反射进阶

黄舟
黄舟 原创
2017-02-24 09:47:47 1001浏览


我们反射通常使用第一种方式,首先来看看Class.forName(clssName):
注意:传入的className必须是类的全路径,否则会报错java.lang.ClassNotFoundException

public static Class<?> forName(String className)                
throws ClassNotFoundException {        
return forName0(className, true, ClassLoader.getCallerClassLoader());
    }

通过调用forName0方法,使用ClassLoader.getCallerClassLoader()来加载ClassLoader

    // Returns the invoker's class loader, or null if none.
    // NOTE: This must always be invoked when there is exactly one intervening
    // frame from the core libraries on the stack between this method's
    // invocation and the desired invoker.
    static ClassLoader getCallerClassLoader() {
        // NOTE use of more generic Reflection.getCallerClass()
        Class caller = Reflection.getCallerClass(3);
        // This can be null if the VM is requesting it        
        if (caller == null) {            
        return null;
        }
        // Circumvent security check since this is package-private        
        return caller.getClassLoader0();
    }

在获取ClassLoader调用claser.getClassLoader0() 这是一个私有包,可以避免安全检查。

 // Package-private to allow ClassLoader access
    native ClassLoader getClassLoader0();

1、ClassLoader到底是个什么东西

我们反射通常使用第一种方式,首先来看看Class.forName(clssName):
注意:传入的className必须是类的全路径,否则会报错java.lang.ClassNotFoundException

public static Class<?> forName(String className)                
throws ClassNotFoundException {        
return forName0(className, true, ClassLoader.getCallerClassLoader());
    }

通过调用forName0方法,使用ClassLoader.getCallerClassLoader()来加载ClassLoader

    // Returns the invoker's class loader, or null if none.
    // NOTE: This must always be invoked when there is exactly one intervening
    // frame from the core libraries on the stack between this method's
    // invocation and the desired invoker.
    static ClassLoader getCallerClassLoader() {
        // NOTE use of more generic Reflection.getCallerClass()
        Class caller = Reflection.getCallerClass(3);
        // This can be null if the VM is requesting it        
        if (caller == null) {            
        return null;
        }
        // Circumvent security check since this is package-private        
        return caller.getClassLoader0();
    }

在获取ClassLoader调用claser.getClassLoader0() 这是一个私有包,可以避免安全检查。

 // Package-private to allow ClassLoader access
    native ClassLoader getClassLoader0();

1、ClassLoader到底是个什么东西

以上就是java之反射进阶的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。