java字符串类的关键字_Java:从字符串加载类

我知道这可能与类加载器有关,但是我找不到一个例子(可能是我正在搜索错误的关键字.

我试图从字符串加载一个类(或方法).该字符串不包含类的名称,而是包含类的代码,例如

class MyClass implements IMath {

public int add(int x, int y) {

return x + y;

}

}

然后做这样的事情:

String s = "class MyClass implements IMath { public int add(int x, int y) { return x + y; }}";

IMath loadedClass = someThing.loadAndInitialize(string);

int result = loadedClass.add(5,6);

现在显然,someThing.loadAndInitialize(string) – 部分是我不知道如何实现的部分.这甚至可能吗?或者更容易运行JavaScripts并以某种方式“给”变量/对象(如x和y)?

谢谢你的任何提示.

解决方法:

使用Java Compiler API. Here是一篇博客文章,向您展示如何做到这一点.

您可以使用临时文件,因为这需要输入/输出文件,或者您可以创建从字符串读取源的JavaFileObject的自定义实现.从javadoc:

/**

* A file object used to represent source coming from a string.

*/

public class JavaSourceFromString extends SimpleJavaFileObject {

/**

* The source code of this "file".

*/

final String code;

/**

* Constructs a new JavaSourceFromString.

* @param name the name of the compilation unit represented by this file object

* @param code the source code for the compilation unit represented by this file object

*/

JavaSourceFromString(String name, String code) {

super(URI.create("string:///" + name.replace('.','/') + Kind.SOURCE.extension),

Kind.SOURCE);

this.code = code;

}

@Override

public CharSequence getCharContent(boolean ignoreEncodingErrors) {

return code;

}

}

获得输出文件(已编译的.class文件)后,可以使用URLClassLoader加载它,如下所示:

ClassLoader loader = new URLClassLoader(new URL[] {myClassFile.toURL());

Class myClass = loader.loadClass("my.package.MyClass");

然后使用以下方法实例化它:

myClass.newInstance();

或使用构造函数.

标签:java,reflection,classloader

来源: https://codeday.me/bug/20191001/1839935.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值