开发者

Thread.currentThread().setContextClassLoader seems not to work correctly

I try to create a jar, use it for compiling but do not ship the jar. I expect the user to provide the jar and pointing my application to this jar.

Imagine the following:

This is my source tree:

main
  Main.java
test
  Test.java

I create two jars:

main.jar
  main
    Main.class
test.jar
  test
    Test.class

My source looks like this:

Main.java

package main;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;

import test.Test;

public class Main {
    public static void main(String[] args) throws Exception {
        URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { new File("test.jar").toURI().toURL() }, null);
        Thread.currentThread().setContextClassLoader(urlClassLoader);
        Test.test();
    }
}

Test.java

package test;

public class Test {
    public static void test() {
        System.out.println("Hello world!");
    }
}

I call the main.jar but without test.jar on the classpath. I would expect the URLClassLoader to load the test.jar and the program to print Hello world!.

But it seems not to use my URLClassLoader but the system classloader instead. I get:

开发者_如何学JAVAException in thread "main" java.lang.NoClassDefFoundError: test/Test
    at main.Main.main(Main.java:14)
Caused by: java.lang.ClassNotFoundException: test.Test
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    ... 1 more

What is my mistake? How to do it right?


For those looking for an answer have a look at How do you change the CLASSPATH within Java? for a workaround and more explanations

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜