Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Use Java Compiler API. <a href="http://mike-java.blogspot.com/2008/03/java-6-compiler-api-tutorial.html" rel="nofollow">Here</a> is a blog post that shows you how to do it.</p> <p>You can use temporary files for this, as this requires input/output file, or you can create custom implementation of <a href="http://docs.oracle.com/javase/6/docs/api/javax/tools/JavaFileObject.html" rel="nofollow">JavaFileObject</a> that reads source from string. From the <a href="http://docs.oracle.com/javase/6/docs/api/javax/tools/JavaCompiler.html" rel="nofollow">javadoc</a>:</p> <pre><code> /** * 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; } } </code></pre> <p>Once you have the output file (which is a compiled <code>.class</code> file), you can load it using <code>URLClassLoader</code> as follows:</p> <pre><code> ClassLoader loader = new URLClassLoader(new URL[] {myClassFile.toURL()); Class myClass = loader.loadClass("my.package.MyClass"); </code></pre> <p>and then instantiate it, using:</p> <pre><code> myClass.newInstance(); </code></pre> <p>or using a <code>Constructor</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload