我知道这可能与类加载器有关,但是我找不到一个例子(可能是我正在搜索错误的关键字.
我试图从字符串加载一个类(或方法).该字符串不包含类的名称,而是包含类的代码,例如
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