gpt4 book ai didi

java - 从 jar 加载一个类

转载 作者:搜寻专家 更新时间:2023-11-01 03:23:55 26 4
gpt4 key购买 nike

我正在尝试从 jar 中加载一个类,我使用的是类加载器。

我有这部分代码来准备类加载器:

private void loadClass(){

try{
JarFile jarFile = new JarFile( Path);
Enumeration e = jarFile.entries();

URL[] urls = { new URL("jar:file:" + Path +"!/") };
classLoader = URLClassLoader.newInstance(urls);


} catch (MalformedURLException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

现在我加载一个类,并尝试获取一个新实例

....           
loadClass();

Class device = classLoader.loadClass( "org.myPackage.MyClass");

MyMotherClass Device = ( MyMotherClass) device.newInstance();
...

MyClass 扩展了 MyMotherClass,当我执行 classLoader.loadClass("org.myPackage.MyClass") 时,MyMotherClass 位于类加载器中。目前,还好。

现在,在 device.newInstance() 中,我得到一个异常。问题是 MyClass 使用的其他类不在类路径中。

我能做什么?

我有另一种方法可以在 classLoader 中加载所有需要的类,但是当我获得新实例时它不起作用。我不能改变 MyClass 和其他人

最佳答案

这是我用来在运行时动态加载 jar 的一些代码。我利用反射来规避这样一个事实,即您实际上不应该这样做(即,在 JVM 启动后修改类路径)。只需将 my.proprietary.exception 更改为合理的内容即可。

    /*
* Adds the supplied library to java.class.path.
* This is benign if the library is already loaded.
*/
public static synchronized void loadLibrary(java.io.File jar) throws my.proprietary.exception
{
try {
/*We are using reflection here to circumvent encapsulation; addURL is not public*/
java.net.URLClassLoader loader = (java.net.URLClassLoader)ClassLoader.getSystemClassLoader();
java.net.URL url = jar.toURI().toURL();
/*Disallow if already loaded*/
for (java.net.URL it : java.util.Arrays.asList(loader.getURLs())){
if (it.equals(url)){
return;
}
}
java.lang.reflect.Method method = java.net.URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{java.net.URL.class});
method.setAccessible(true); /*promote the method to public access*/
method.invoke(loader, new Object[]{url});
} catch (final NoSuchMethodException |
java.lang.IllegalAccessException |
java.net.MalformedURLException |
java.lang.reflect.InvocationTargetException e){
throw new my.proprietary.exception(e.getMessage());
}
}

关于java - 从 jar 加载一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20549408/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com