Compiling in Memory

I am reading a book Java 6 Platform Revealed which describes using of Compiler API. Unfortunately Compiler API was changed during development of Mustang.

This sample stopped to work although I renamed names of classes into new ones.

I am able to compile the source of HelloWorld class, but I don't know how to invoke a new instance of this successfully compiled class (I get permanent ClassNotFoundException).

How to get it work?

Thank you for your help

Cavity

PS. I don't want to use extern files (as described here http://javainsel.blogspot.com/2006/03/example-for-using-java-6-compiler-api.html), I would like to make it as fast as possible (=in memory).

-

Java SE 6 final

import javax.tools.*;

import java.io.IOException;

import java.io.PrintWriter;

import java.io.StringWriter;

import java.lang.reflect.InvocationTargetException;

import java.net.URI;

import java.util.Arrays;

publicclass CompileSource{

private CompileSource(){

}

publicstaticvoid main(String args[])throws IOException{

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

DiagnosticCollector<JavaFileObject> diagnostics =

new DiagnosticCollector<JavaFileObject>();

StringWriter writer =new StringWriter();

PrintWriter out =new PrintWriter(writer);

out.println("public class HelloWorld {");

out.println(" public static void main(String args[]) {");

out.println("System.out.println(\"Hello, World\");");

out.println(" }");

out.println("}");

out.close();

JavaFileObject file =

new JavaSourceFromString("HelloWorld", writer.toString());

Iterable<?extends JavaFileObject> compilationUnits =

Arrays.asList(file);

JavaCompiler.CompilationTask task = compiler.getTask(

null, null, diagnostics, null, null, compilationUnits);

boolean success = task.call();

for (Diagnostic diagnostic : diagnostics.getDiagnostics())

System.console().printf(

"Code: %s%n" +

"Kind: %s%n" +

"Position: %s%n" +

"Start Position: %s%n" +

"End Position: %s%n" +

"Source: %s%n" +

"Message: %s%n",

diagnostic.getCode(), diagnostic.getKind(),

diagnostic.getPosition(), diagnostic.getStartPosition(),

diagnostic.getEndPosition(), diagnostic.getSource(),

diagnostic.getMessage(null));

System.out.println("Success: " + success);

if (success){

try{

System.out.println("--Output--");

Class.forName("HelloWorld").getDeclaredMethod("main",

new Class[]{String[].class}).invoke(null,new Object[]{null});

System.out.println("--Output--");

}catch (ClassNotFoundException e){

System.err.println("Class not found: " + e);

}catch (NoSuchMethodException e){

System.err.println("No such method: " + e);

}catch (IllegalAccessException e){

System.err.println("Illegal access: " + e);

}catch (InvocationTargetException e){

System.err.println("Invocation target: " + e);

}

}

}

staticpublicclass JavaSourceFromStringextends SimpleJavaFileObject{

final String code;

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;

}

}

}

Message was edited by:

Cavity

[6350 byte] By [Cavitya] at [2007-11-26 12:46:14]
# 1
You need a class loader.See: https://openjdk.dev.java.net/source/browse/openjdk/compiler/trunk/test/tools/javac/api/evalexpr/and https://openjdk.dev.java.net/compiler/guide/compilerAPI.html
PeterAhea at 2007-7-7 16:26:15 > top of Java-index,Developer Tools,Java Compiler...
# 2
This is exactly what I was looking for the whole day. Thank you very much Peter.Unfortunately I cannot give you your deserved dukes :-((.This forum is buggy, i cannot log in under my previous account :-((( and reseting password without "security" question does not work
Vitya at 2007-7-7 16:26:15 > top of Java-index,Developer Tools,Java Compiler...
# 3
It's OK. I'm not in it for the dukes ;-)Anyways, I think I used the wrong link for the guide. Use this link instead:https://openjdk.dev.java.net/nonav/compiler/guide/compilerAPI.html(looks best in Firefox)
PeterAhea at 2007-7-7 16:26:15 > top of Java-index,Developer Tools,Java Compiler...