且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java:从字符串加载类

更新时间:2022-06-25 22:06:03

使用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();

或使用构造函数