我在运行时从外部MyClass.class文件成功加载了一个类,并假设我知道它们的名称,就可以调用它的方法.
我遇到的问题是我无法弄清楚如何将参数传递给正在加载的类的构造函数.
如何修改此参数以将参数传递给MyClass的构造函数?另外,如何访问MyClass的公共变量infoToAccess?
这是我正在使用的文件. (请记住,ClassLoaderExample.pde是为Processing编写的,但是除了sketchPath(“”)之外,并且缺少主要功能,它是相同的.
ClassLoaderExample.pde:加载类的主文件:
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.MalformedURLException;
import java.lang.ClassLoader;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
/////// FILE STRUCTURE /////
// ClassLoaderExample //
// --this file //
// --tmp //
// ----MyClass.class //
////////////////////////////
// TODO
// Send parameter to MyClass constructor (by reference)
// Get public int number from MyClass
void setup()
{
String className = "MyClass";
Object instance;
Method updateMethod;
// sketchPath("") returns the directory this file is in
File file = new File(sketchPath(""));
try
{
URL url = file.toURL();
URL[] urls = new URL[]{url};
ClassLoader classLoader = new URLClassLoader(urls);
Class<?> loadedClass = classLoader.loadClass("tmp."+className);
try
{
instance = loadedClass.newInstance();
updateMethod = loadedClass.getDeclaredMethod("update");
// Calls MyClass's update() method
try
{
updateMethod.invoke(instance);
}
catch (InvocationTargetException e) {System.out.println(e);}
catch (IllegalAccessException e) {System.out.println(e);}
}
catch (InstantiationException e) {System.out.println(e);}
catch (IllegalAccessException e) {System.out.println(e);}
catch (NoSuchMethodException e) {System.out.println(e);}
}
catch (MalformedURLException e) {System.out.println(e);}
catch (ClassNotFoundException e) {System.out.println(e);}
}
MyClass.java:我正在加载的类:
package tmp;
public class MyClass
{
public int infoToAccess = 1337;
public MyClass(int i)
{
System.out.println("MyClass constructor was called with numebr: " + i);
}
public void update()
{
System.out.println("Update was called.");
}
}
感谢您对此的任何帮助!
解决方法:
您可以使用加载的类来获取构造函数
您需要使用它来创建新实例.
import java.lang.reflect.Constructor;
...
Class<?> loadedClass = classLoader.loadClass("tmp."+className);
try {
Constructor<?> ctor=loadedClass.getConstructor(int.class);
ctor.newInstance(42);
...
}
...