我在运行时成功地从外部 MyClass.class
文件加载了一个类,并且能够调用它的方法,假设我知道它们的名称,我确实知道。
我遇到的问题是我不知道如何将参数传递给我正在加载的类的构造函数。
如何修改它以将参数传递给 MyClass
的构造函数?另外,如何访问 MyClass
的公共(public)变量:infoToAccess
?
这是我正在处理的文件。 (请记住,ClassLoaderExample.pde 是为 Processing 编写的,但除了 sketchPath("")
和缺少 main
函数外,它是相同的。
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);
...
}
...
关于java - 我可以将参数传递给动态创建的类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31958158/