Note that there are some explanatory texts on larger screens.

plurals
  1. POCompiled a class, but where is it?
    text
    copied!<p>I'm not an expert in Java and I'm pretty new to the whole concept of compiling and running dynamic generated code, which is so simple in other languages, expecially script languages like Javascript and PHP.</p> <p>I'm following this snippet of code: <a href="http://www.java2s.com/Code/Java/JDK-6/CompilingfromMemory.htm" rel="nofollow">http://www.java2s.com/Code/Java/JDK-6/CompilingfromMemory.htm</a> and I made something like this:</p> <pre><code>private final String = "GeneratedClass_" + Long.toHexString(random.nextLong()); private Method compileCode(String code) { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if (compiler == null) return null; DiagnosticCollector&lt;JavaFileObject&gt; diagnostics = new DiagnosticCollector&lt;JavaFileObject&gt;(); JavaFileObject source = new JavaSource(className, code); Iterable&lt;? extends JavaFileObject&gt; compilationUnits = Arrays.asList(source); CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits); if (!task.call()) return null; try { return Class.forName(className).getDeclaredMethods()[0]; } catch (ClassNotFoundException e) {} return null; } private class JavaSource extends SimpleJavaFileObject { final String code; JavaSource(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>Just imagine that the string code is something like</p> <pre><code>"public class GeneratedClass_65ce701239c32ce0 { public String hello() { return "Hello, world!"; } }" </code></pre> <p>It works well until that Class.forName which throws a ClassNotFoundException. I'm puzzled since it doesn't seem I cut something important from the snippet: so, the class was compiled but where has it gone?</p> <p>I read something about using a different class loader, but since, like I said, I'm pretty new to all this stuff I don't know where to head and how to use it, and how should I define my own extension of ClassLoader. The only thing I know is that everything seems quite complicated to me...</p> <p>Using Eclipse Indigo in Windows 7 and JDK 1.7.</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