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

我在运行时从外部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.");

}

}

感谢您对此的任何帮助!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值