我有一堆已经加载的类,并且已经在类上完成了newInstance()。我想重用这些类,而无需再次执行newInstance()并重用它们的当前状态。是否有一种方法来替换newInstance()的使用,以便我可以重用已经实例化的类而无需重新创建它们(从而丢失所有状态)。我应该怎么做呢?
List<Class> classes = null;
private void parseCP(File loadPath) {
try {
// Convert loading path to a URL
URL url = loadPath.toURI().toURL();
URL[] urls = new URL[]{url};
// Create a new class loader with the directory
ClassLoader cl = new URLClassLoader(urls);
classes = getClassesFromFolder(loadPath.getPath(), cl);
System.out.println("Classes discovered: " + classes.size());
for (Class i : classes) {
System.out.println("Looking into class: " + i.getName());
Object obj = i.newInstance();
// Call load() to get HttpFunctions to register their main and sub functions.
Method loadMethod = i.getMethod("load", null);
Object loadRes = loadMethod.invoke(obj, null);
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | IOException | NoSuchMethodException e) {
e.printStackTrace();
}
}
public Object invoke(String classname, String method, Object args) {
Object res = null;
try {
for (Class i : classes) {
if (i.getName().equals(classname)) {
Object obj = i.newInstance(); //<--- How do I NOT create newInstance but reuse them ?
Class[] cargs = new Class[1];
cargs[0] = Object.class;
Method loadMethod;
if (args != null) {
loadMethod = i.getMethod(method, cargs);
} else {
loadMethod = i.getMethod(method, null);
}
if (loadMethod != null) {
if (args == null) {
res = loadMethod.invoke(obj);
} else {
res = loadMethod.invoke(obj, args);
}
}
}
}
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
return res;
}
注意:我之前有一篇关于类加载的帖子,但这两篇文章背后的问题并不相同。
答案 0 :(得分:3)
您可以使用HashMap存储对象
public static HashMap<Class, Object> instances = new HashMap<Class, Object>();
public Object getInstance(Class clazz) {
if (instances.constainsKey(clazz)) {
return instances.get(clazz);
} else {
Object o = clazz.newInstance();
instances.put(clazz, o);
return o
}
}
但我实际上并不了解目的,似乎有更好的方法来解决你的问题。