【发布时间】:2015-01-12 19:15:53
【问题描述】:
我创建了一个自定义 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,我事先无法知道该类的名称是什么。如何避免使用字符串作为参数?
【问题讨论】:
-
为什么要避免使用字符串?
-
因为我想更改内容。类名并不总是相同的。
-
嗯?那么你会如何识别这个类呢?
-
这就是我要问的:-)
-
不,你想要哪门课?你能描述一下你想选择一个班级的标准吗?
标签: java class classloader in-memory