Java: Load class from string

孤街浪徒 提交于 2019-11-29 08:53:09

Use Java Compiler API. Here is a blog post that shows you how to do it.

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;
       }
   }

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");

and then instantiate it, using:

    myClass.newInstance();

or using a Constructor.

You can use Rhino and JavaScript in JDK 7. That might be a good way to do it.

invokedynamic is coming....

If you want to stick with Java, you need something to parse the source and turn it into byte code - something like cglib.

You could compile it using JavaCompiler but I suggest you to use Groovy for this run-time class creation. It would be much easier.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!