2

我知道这可能与类加载器有关,但是我找不到示例(可能是我在谷歌搜索错误的关键字。

我正在尝试从字符串加载类(或方法)。该字符串不包含类的名称,而是类的代码,例如

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)- 部分是我不知道如何实现的部分。这甚至可能吗?或者运行 JavaScript 并以某种方式“给出”变量/对象(如 x 和 y)会更容易吗?

谢谢你的任何提示。

4

4 回答 4

8

使用 Java 编译器 API。是一篇博客文章,向您展示了如何做到这一点。

您可以为此使用临时文件,因为这需要输入/输出文件,或者您可以创建从字符串读取源代码的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();

或使用Constructor.

于 2012-06-04T14:29:42.450 回答
3

可以在 JDK 7 中使用 Rhino 和 JavaScript。这可能是一个好方法。

invokedynamic来了....

如果你想坚持使用 Java,你需要一些东西来解析源代码并将其转换为字节码——比如 cglib。

于 2012-06-04T14:28:07.457 回答
0

你可以使用它来编译它,JavaCompiler但我建议你使用它来Groovy创建这个运行时类。这会容易得多。

于 2012-06-04T14:31:19.303 回答
0

首先你需要编译你的代码,例如使用编译器 API:( http://www.accordess.com/wpblog/an-overview-of-java-compilation-api-jsr-199/ , http://docs .oracle.com/javase/6/docs/api/javax/tools/package-summary.html)。并在使用 ClassLoader 加载编译后的类(http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/ClassLoader.html

于 2012-06-04T14:31:29.843 回答