Java:从字符串加载类 [英] Java: Load class from string
问题描述
我知道这可能与类加载器有关,但是我找不到一个例子(可能是我正在搜索错误的关键字。
I know this has probably something to do with class loaders, however I couldn't find an example (it might be I'm google-ing for the wrong keywords.
我正在尝试从字符串中加载一个类(或方法)。该字符串不包含类的名称,而是包含类的代码,例如
I am trying to load a class (or a method) form a string. The string doesn't contain the name of a class, but the code for a class, e.g.
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会更容易吗?并以某种方式给变量/ ob jects(比如x和y)?
Now obviously, the someThing.loadAndInitialize(string)
- part is the one I don't know how to achieve. Is this even possible? Or would it be easier to run JavaScripts and somehow "give" the variables / objects (like x and y)?
感谢您的任何提示。
推荐答案
使用Java Compiler API。 此处是一篇博文,显示你怎么做。
Use Java Compiler API. Here is a blog post that shows you how to do it.
你可以使用临时文件,因为这需要输入/输出文件,或者你可以创建 JavaFileObject 从字符串中读取源代码。来自 javadoc :
You can use temporary files for this, as this requires input/output file, or you can create custom implementation of JavaFileObject that reads source from string. From the 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
file),您可以使用 URLClassLoader
加载它,如下所示:
Once you have the output file (which is a compiled .class
file), you can load it using URLClassLoader
as follows:
ClassLoader loader = new URLClassLoader(new URL[] {myClassFile.toURL());
Class myClass = loader.loadClass("my.package.MyClass");
然后实例化它,使用:
myClass.newInstance();
或使用构造函数
。
这篇关于Java:从字符串加载类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!