javaeclipsebuildjarjava-compiler-api

JavaCompiler not working in Jar


I got a java program which uses a JavaCompiler to generate new class files.

I use jdk 1.6 within eclipse and this works fine.

But when I export this as jar file and wan't to compile some .java files it gives me a null error (because there is no compiler in the system used jre?). is there a way to provide the compiler within the jar file?

File fRun = new File("someFile.java");
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
Iterable<String> options = Arrays.asList( new String[] { "-d", currentDir+"\\bin\\"} );
Iterable<? extends JavaFileObject> compUnits =  fileManager.getJavaFileObjects(fRun);
Boolean compRes = compiler.getTask(null, fileManager, null, options, null, compUnits).call();           

if(compRes == true){
    System.out.println("Compilation has succeeded");
    fileManager.close();
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    Class<?> compiledClass = cl.loadClass(someFile);
    cRun = compiledClass;
}else{
    System.out.println("Compilation error");
    fileManager.close();
    throw new Exception("Compilation Error");
}

Solution

  • This will help you--> http://weblogs.java.net/blog/kirillcool/archive/2005/05/using_java_comp.html Look for "...The standard technique for compiling Java source files in regular standalone application is to use the tools.jar that resides under jdk/lib ..."