[英]Class loading class from jar
This is the common approach with working with loading class dynamically: 这是动态处理类的常用方法:
try {
File file = new File(JAR_FILE);
String classToLoad = "com.mycompany.MyClass";
URL jarUrl = new URL("jar", "","file:" + file.getAbsolutePath()+"!/");
URLClassLoader loader = new URLClassLoader(new URL[] {jarUrl}, Thread.currentThread().getContextClassLoader());
Class c = loader.loadClass(classToLoad);
} catch (Exception e) {
e.printStackTrace();
}
However, I need an approach where: 但是,我需要一种方法:
You will have to create your own class loader. 您将必须创建自己的类加载器。
Something like this, basic idea in pseudo code: 伪代码的基本思想是这样的:
class MyClassLoader extends ClassLoader {
public Class findClass(String name) {
byte[] b = loadClassData(name);
return defineClass(name, b, 0, b.length);
}
private byte[] loadClassData(String name) {
JarInputStream jis = new JarInputStream(new ByteArrayInputStream(bytearrayJarData));
JarEntry entry = jis.getNextJarEntry();
while (entry != null) {
//compare entry to requested class
// if match, return Byte data
// else entry = jis.getNextJarEntry();
}
return null; // nothing found
}
}
Write your own ClassLoader
and override findClass()
. 编写自己的ClassLoader
并覆盖findClass()
。 There you can use defineClass()
to load your byte[]
. 在那里,您可以使用defineClass()
来加载byte[]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.