我想启动一个java子进程,它具有与当前java进程相同的java classpath和动态加载的类。以下是不够的,因为它不包含任何动态加载的类:使用父进程启动Java子进程类路径
String classpath = System.getProperty("java.class.path");
目前我在寻找与下面的代码所需要的每个类。但是,在某些机器上,某些类/库会失败,源变量为空。是否有更可靠和更简单的方法来获取当前jvm进程使用的库的位置?
String stax = ClassFinder.classPath("javax.xml.stream.Location");
public static String classPath(String qualifiedClassName) throws NotFoundException {
try {
Class qc = Class.forName(qualifiedClassName);
CodeSource source = qc.getProtectionDomain().getCodeSource();
if (source != null) {
URL location = source.getLocation();
String f = location.getPath();
f = URLDecoder.decode(f, "UTF-8"); // decode URL to avoid spaces being replaced by %20
return f.substring(1);
} else {
throw new ClassFinder().new NotFoundException(qualifiedClassName+" (unknown source, likely rt.jar)");
}
} catch (Exception e) {
throw new ClassFinder().new NotFoundException(qualifiedClassName);
}
}
出于好奇:你是怎么想出这种方法的? – 2010-01-12 16:24:55
我是怎么想出这种方法的?我发现它在网上的某个地方,不记得现在在哪里。 我认为这个问题真的归结为,为什么ProtectionDomain .getCodeSource()有时返回null。 APIs文档没有用,他们只是说该方法可能会返回null。 – 2010-01-12 17:15:40