到目前为止,我看到的自定义ClassLoader示例涉及子类化URLClassLoader,并使用该特定实例加载资源中的类.
我徒劳地试图寻找替换SystemClassLoader的替代方法,以便可以为不在类路径中的类查询我的ClassLoader.
我试过了Thread.currentThread().setContextClassLoader,但似乎没有用.
它甚至可能吗?
我正在尝试在运行时切换类加载器:
public class Test {
public static void main(String[] args) throws Exception {
final InjectingClassLoader classLoader = new InjectingClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
Thread thread = new Thread("test") {
public void run() {
System.out.println("running...");
// approach 1
ClassLoader cl = TestProxy.class.getClassLoader();
try {
Class c = classLoader.loadClass("classloader.TestProxy");
Object o = c.newInstance();
c.getMethod("test", new Class[] {}).invoke(o);
} catch (Exception e) {
e.printStackTrace();
}
// approach 2
new TestProxy().test();
};
};
thread.setContextClassLoader(classLoader);
thread.start();
}
}
Run Code Online (Sandbox Code Playgroud)
和:
public class TestProxy {
public void test() {
ClassLoader …Run Code Online (Sandbox Code Playgroud)