Java 내에서 CLASSPATH를 어떻게 변경합니까?
Java 프로세스 내에서 Java 프로세스의 CLASSPATH를 어떻게 변경합니까?
"왜 그렇게 하시겠습니까?"라고 묻기 전에 곧 설명하겠습니다.
Clojure REPL이 실행 중일 때 Clojure 소스 파일 을로드하기 위해 CLASSPATH에 더 많은 jar가 필요한 것이 일반적 이며, Clojure 자체를 다시 시작할 필요없이 수행하고 싶습니다 (슬라임에서 사용할 때 실제로는 옵션이 아닙니다). Emacs에서).
그것이 이유이지만이 질문에 이상한 언어의 어떤 이상한 편집기로 태그를 붙이고 대답을 할 수있는 대다수의 Java 개발자가 무시하는 것을 원하지 않습니다.
업데이트 Q4 2017 :로 주석 아래 vda8888 , 자바 (9)에서, 시스템은 java.lang.ClassLoader
더 이상 없습니다 java.net.URLClassLoader
.
" Java 9 마이그레이션 가이드 : 가장 일반적인 7 가지 과제 "를 참조하십시오.
방금 설명한 클래스 로딩 전략은 새로운 유형으로 구현되었으며 Java 9에서는 애플리케이션 클래스 로더가 해당 유형입니다.
즉,URLClassLoader
더 이상이 아니므로 가끔(URLClassLoader) getClass().getClassLoader()
또는(URLClassLoader) ClassLoader.getSystemClassLoader()
시퀀스가 더 이상 실행되지 않습니다.
java.lang.ModuleLayer 는 (클래스 경로 대신) 모듈 경로 에 영향을주기 위해 사용되는 대체 접근 방식 입니다. 예를 들어 " Java 9 모듈-JPMS 기본 사항 "을 참조하십시오 .
Java 8 이하의 경우 :
몇 가지 일반적인 의견 :
(작동이 보장되는 이식 가능한 방식으로 아래 참조) 시스템 클래스 경로를 변경할 수 없습니다. 대신 새 ClassLoader를 정의해야합니다.
ClassLoader는 계층 적 방식으로 작동하므로 클래스 X에 대한 정적 참조를 만드는 모든 클래스는 X와 동일한 ClassLoader 또는 자식 ClassLoader에로드되어야합니다. 사용자 정의 ClassLoader를 사용하여 시스템 ClassLoader 링크에 의해 코드를 제대로로드하도록 만들 수 없습니다. 따라서 찾은 추가 코드 외에도 사용자 정의 ClassLoader에서 기본 애플리케이션 코드가 실행되도록 정렬해야합니다.
(그렇게 말하면, 이 확장URLClassLoader
예제의 주석에서 모든 언급 이 깨 졌습니다 . )
자신의 ClassLoader를 작성하지 않고 대신 URLClassLoader를 사용하는 것을 고려할 수 있습니다. 상위 클래스 로더 URL에 없는 URL로 URLClassLoader를 만듭니다 .
URL[] url={new URL("file://foo")};
URLClassLoader loader = new URLClassLoader(url);
더 완벽한 솔루션이 될 것이다 :
ClassLoader currentThreadClassLoader
= Thread.currentThread().getContextClassLoader();
// Add the conf dir to the classpath
// Chain the current thread classloader
URLClassLoader urlClassLoader
= new URLClassLoader(new URL[]{new File("mtFile").toURL()},
currentThreadClassLoader);
// Replace the thread classloader - assumes
// you have permissions to do so
Thread.currentThread().setContextClassLoader(urlClassLoader);
JVM 시스템 클래스 로더가 URLClassLoader (모든 JVM에 해당되지 않을 수 있음)라고 가정하면 리플렉션을 사용하여 실제로 시스템 클래스 경로를 수정할 수 있습니다 ... (하지만 그것은 해킹입니다;)) :
public void addURL(URL url) throws Exception {
URLClassLoader classLoader
= (URLClassLoader) ClassLoader.getSystemClassLoader();
Class clazz= URLClassLoader.class;
// Use reflection
Method method= clazz.getDeclaredMethod("addURL", new Class[] { URL.class });
method.setAccessible(true);
method.invoke(classLoader, new Object[] { url });
}
addURL(new File("conf").toURL());
// This should work now!
Thread.currentThread().getContextClassLoader().getResourceAsStream("context.xml");
나는 당신이 할 수 있다고 믿지 않습니다-올바른 일은 (내 생각에) 새로운 경로로 새로운 클래스 로더를 만드는 것입니다. 또는 클래스 경로 (해당 로더에 대한)를 동적으로 변경할 수있는 자체 클래스 로더를 작성할 수 있습니다.
자신 만의 클래스 로더를 작성할 필요가 없습니다! 있다 clojure.lang.DynamicClassLoader은 .
http://blog.japila.pl/2011/01/dynamically-redefining-classpath-in-clojure-repl/
You may want to look into using java.net.URLClassLoader. It allows you to programmatically load classes that weren't originally in your classpath, though I'm not sure if that's exactly what you need.
It is possible as seen from the two links below, the method VonC gives seems to be the best but check out some of these posts and google for "Java Dynamic Classpath" or "Java Dynamic Class Loading" and find out some info from there.
I'd post in more depth but VonC has pretty much done the job.
From Dynamic loading of class and Jar files.
Also check this sun forum post.
String s="java -classpath abcd/ "+pgmname+" "+filename;
Process pro2 = Runtime.getRuntime().exec(s);
BufferedReader in = new BufferedReader(new InputStreamReader(pro2.getInputStream()));
is an example of changin the classpath in java program
참고URL : https://stackoverflow.com/questions/252893/how-do-you-change-the-classpath-within-java
'IT TIP' 카테고리의 다른 글
TortoiseSVN에 보관 하시겠습니까? (0) | 2020.12.08 |
---|---|
특정 열의 데이터가 포함 된 마지막 행을 어떻게 찾을 수 있습니까? (0) | 2020.12.08 |
Greasemonkey 네임 스페이스는 무엇에 필요합니까? (0) | 2020.12.08 |
NoInitialContextException 오류의 의미 (0) | 2020.12.08 |
Moq'ing 방법 어디서 표현 (0) | 2020.12.08 |