[英]load class not in classpath dynamically in web application - without using custom classloader
[英]Loading a class with custom ClassLoader without using a String
我创建了一个自定义的ClassLoader,并希望加载一个类。 我现在正在使用此代码从Jar中加载类:
ByteArrayInputStream byteIS = new ByteArrayInputStream(data);
JarInputStream jarIS = new JarInputStream(byteIS);
JarEntry je;
je = jarIS.getNextJarEntry();
byte[] classbytes = new byte[(int) je.getSize()];
jarIS.read(classbytes, 0, classbytes.length);
jarIS.close();
CustomClassLoader classLoader = new CustomClassLoader();
classLoader.setClassContent(classbytes);
Class c = classLoader.findClass("Main");
Object object = c.newInstance();
Method[] methods = object.getClass().getMethods();
Object returnValue = methods[0].invoke(null, new Object[]{new String[]{}});
在上面的示例中,您可以清楚地看到我正在尝试加载Main类。 现在想象一下,我的朋友也创建了一个Jar,我事先无法知道类的名称。 如何避免将String用作参数?
您可能需要看一下ServiceLoader API 。 您可以为您不知道先验的服务实现(类)定义一个通用接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.