我可以将参数传递给动态创建的类吗?

时间:2015-08-12 07:02:13

标签: java parameter-passing processing classloader urlclassloader

我在运行时从外部MyClass.class文件成功加载了一个类,并且能够调用它的方法,假设我知道它们的名称,我这样做。

我遇到的问题是我无法弄清楚如何将参数传递给我正在加载的类的构造函数。

如何修改此选项以将参数传递给MyClass的构造函数?另外,我如何访问MyClass的公共变量: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.");
    }
}

感谢您对此提供任何帮助!

4 个答案:

答案 0 :(得分:3)

您可以使用您加载的类来获取构造函数 您需要使用它来创建新实例。

import java.lang.reflect.Constructor;

...

Class<?> loadedClass = classLoader.loadClass("tmp."+className);
try {
  Constructor<?> ctor=loadedClass.getConstructor(int.class);
  ctor.newInstance(42);
  ...
}
...

答案 1 :(得分:1)

您需要对所提到的两件事情使用反思:

Class<?> loadedClass = classLoader.loadClass("tmp." + className);
Object oInstance = null;
try {
    Constructor<?> c = loadedClass.getConstructor(Integer.class);
    oInstance = c.newInstance(10);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    //Handle the possibility that you cannot access this constructor
}

要访问对象的公共字段:

try {
    Field field = loadedClass.getField("infoToAccess");
    int fieldValue = field.getInt(oInstance);
} catch (NoSuchFieldException | IllegalAccessException e) {
    //Handle the possibility that you cannot access this field
}

答案 2 :(得分:0)

正如我在评论中写的链接中所提到的,您可以在此调用中传递参数

updateMethod = loadedClass.getDeclaredMethod(&#34;更新&#34;,参数转到此处);

然后你应该能够用参数调用方法

答案 3 :(得分:0)

如果要将参数传递给构造函数,则不能使用getInstance(),您必须获取构造函数对象并在那里传递参数。

示例:

Constructor constructor = aClass.getConstructor(new Class[]{String.class});
MyObject myObject = (MyObject) constructor.newInstance("constructor-arg1");

请参阅此处的教程:Java Reflection - Constructors

相关问题