내가 런타임에 클래스 로더를 전환하기 위해 노력하고있어 :는 변경 클래스 로더
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();
}
}
과 :
public class TestProxy {
public void test() {
ClassLoader tcl = Thread.currentThread().getContextClassLoader();
ClassLoader ccl = ClassToLoad.class.getClassLoader();
ClassToLoad classToLoad = new ClassToLoad();
}
}
(InjectingClassLoader는 org.apache.bcel.util를 확장하는 클래스입니다 .ClassLoader 부모에게 요청하기 전에 클래스의 수정 된 버전을로드해야합니다.
e는 "접근 1"과 "접근 2"의 결과를 똑같이 만들지 만 처럼 보입니다. thread.setContextClassLoader (classLoader)은 아무 것도하지 않고 "접근 2"는 항상 시스템 클래스 로더를 사용합니다 (tcl 및 디버깅하는 동안 ccl 변수).
모든 클래스가 새 스레드를 사용하여 주어진 클래스 로더를로드 할 수 있습니까?
Nit : "반사적으로". 컨텍스트 클래스 로더에 관한 질문에 혼란이 있다면 setContextClassLoader는 스레드가 설정해야하는 작업 (예 : SAXParser 만들기, JNDI 조회 수행 등)을 수행하지 않는 한 아무런 효과가 없다고 말할 수 있습니다. –
수정 됨; 반사적으로 -> 반사적으로. 감사. –