简体   繁体   English

为什么我不能通过ExtClassLoader加载类?

[英]Why can't I load my class by ExtClassLoader?

This is the structure of my Java project: 这是我的Java项目的结构:

package: com.study.test
              ---- HelloWorld.java
              ---- Test.java

The content of HelloWorld.java : HelloWorld.java的内容:

package com.study.test;

public class HelloWorld {}

The content of Test.java : Test.java的内容:

package com.study.test;

public class Test {

    public static void main(String[] args) {
        System.out.println(System.getProperty("java.ext.dirs"));
        System.out.println(HelloWorld.class.getClassLoader());
    }

}

The value of the " java.ext.dirs " is: java.ext.dirs ”的值是:

D:\glassfish4\jdk7\jre\lib\ext;C:\windows\Sun\Java\lib\ext

I put the class file HelloWorld.class in directory: 我将类文件HelloWorld.class放在目录中:

D:\glassfish4\jdk7\jre\lib\ext\com\study\test

but the output of " System.out.println(HelloWorld.class.getClassLoader()); " is: 但是“ System.out.println(HelloWorld.class.getClassLoader()); ”的输出是:

sun.misc.Launcher$AppClassLoader@70a0afab

Why the class HelloWorld isn't loaded by ExtClassLoader? 为什么ExtClassLoader无法加载类HelloWorld? ExtClassLoader is the parent class loader of AppClassLoader. ExtClassLoader是AppClassLoader的父类加载器。

The extension classloader load only classes from within Jar files. 扩展类加载器仅从Jar文件中加载类。

assume following structure 采取以下结构

src/Test.java
src/HelloWorld.java

amend Test.java as ( edit this is not really necessary, only to show that the resolving is not done during compile time) Test.java修改为(实际上并不需要编辑 ,只是为了表明在编译期间未完成解析)

package com.study.test;
public class Test {
    public static void main(String[] args) throws Exception {
        System.out.println(System.getProperty("java.ext.dirs"));
        System.out.println(Class.forName("com.study.test.HelloWorld")
            .getClassLoader());
    }
}

compile them 编译它们

mkdir bin/
javac -d bin/ src/Test.java src/HelloWorld.java

create a Jar file containing the classes 创建一个包含类的Jar文件

jar cf test-hello.jar -C bin/ .

verify the content of the Jar file 验证Jar文件的内容

jar tf test-hello.jar

output 输出

META-INF/                       
META-INF/MANIFEST.MF            
com/                            
com/study/                      
com/study/test/                 
com/study/test/HelloWorld.class 
com/study/test/Test.class       

move the test-hello.jar in the extension directory test-hello.jar移动到扩展目录中

mv test-hello.jar D:\glassfish4\jdk7\jre\lib\ext

run your class Test 运行您的课程Test

java com.study.test.Test

output similar (the directories where copied from your questin) 输出类似(从您的查询中复制的目录)

D:\glassfish4\jdk7\jre\lib\ext;C:\windows\Sun\Java\lib\ext
sun.misc.Launcher$ExtClassLoader@70dea4e

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM