关于JAVA类加载器。
高洛峰
高洛峰 2017-04-18 10:48:13
0
1
380
public static <T> T classLoader(String className) throws Exception {
        ClassLoader myClassLoader = new ClassLoader() {
            @Override
            protected Class<?> findClass(String name) throws ClassNotFoundException {
                try {
                    //获取类文件名
                    String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
                    InputStream inputStream = getClass().getResourceAsStream(fileName);
                    if (inputStream == null) {
                        return super.findClass(fileName);
                    }
                    byte[] bytes = new byte[inputStream.available()];
                    inputStream.close();
                    return defineClass(name, bytes, 0, bytes.length);
                } catch (IOException e) {
                    throw new ClassNotFoundException();
                }
            }
        };
        return (T) myClassLoader.loadClass(className).newInstance();
    }
public static void main(String[] args) throws Exception {
        //测试1
        Object obj2 = classLoader("com.myweb.reflect.classloader.ClassLoaderTest");
        System.out.println(obj2.getClass());
        System.out.println(obj2 instanceof com.myweb.reflect.classloader.ClassLoaderTest);
        
        //测试2
        ClassLoader myClassLoader = new ClassLoader() {
            @Override
            protected Class<?> findClass(String name) throws ClassNotFoundException {
                try {
                    //获取类文件名
                    String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
                    InputStream inputStream = getClass().getResourceAsStream(fileName);
                    if (inputStream == null) {
                        return super.findClass(fileName);
                    }
                    byte[] bytes = new byte[inputStream.available()];
                    inputStream.close();
                    return defineClass(name, bytes, 0, bytes.length);
                } catch (IOException e) {
                    throw new ClassNotFoundException();
                }
            }
        };

        Object obj3 = myClassLoader.loadClass("com.myweb.reflect.classloader.ClassLoaderTest");
        System.out.println(obj3.getClass());
        System.out.println(obj3 instanceof com.myweb.reflect.classloader.ClassLoaderTest);
}

输出:
class com.myweb.reflect.classloader.ClassLoaderTest
true
class java.lang.Class
false

为什么两段相同的代码,只是一个单独提取出来,输出就不一样了呢?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

모든 응답(1)
Peter_Zhu

두 개의 동일한 코드 조각이 확실합니까?
첫 번째 코드에 여러 문장이 있습니다
return (T) myClassLoader.loadClass(className).newInstance();

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!