Running from Jar
Running the application from jar (I packaged it using: mvn package ) will compile the class
file Test.class next to the jar
file.
D:\compiling-string-example\target>dir
Volume in drive D is Data
Volume Serial Number is 68F9-EDFA
Directory of D:\compiling-string-example\target
12/27/2015 05:04 PM <DIR> .
12/27/2015 05:04 PM <DIR> ..
12/27/2015 04:24 PM <DIR> classes
12/27/2015 05:01 PM 9,700
compiling-string-example-1.0-SNAPSHOT.jar
12/27/2015 04:24 PM <DIR> generated-sources
12/27/2015 04:24 PM <DIR> maven-archiver
12/27/2015 05:01 PM <DIR> surefire
12/27/2015 04:08 PM 421 Test.class
2 File(s) 10,121 bytes
6 Dir(s) 84,648,378,368 bytes free
That means we can run it like this:
D:\compiling-string-example\target>java -cp
.;compiling-string-example-1.0-SNAPSHOT.jar
com.logicbig.example.StringCompilation
testing
Also be careful about a JRE
1.7 and JRE 1.8
bug. If you have a null pointer exception on the compiler instance (ToolProvider.getSystemJavaCompiler() can
return null), you have to set JDK path instead of JRE. JRE 6.x works fine.
Setting an Explicit Output Path
We can control the class output folder by using fileManager.setLocation .
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics =
new DiagnosticCollector<>();
StandardJavaFileManager fileManager =
compiler.getStandardFileManager(diagnostics, null, null);
//should be platform independent path
//also the folder should already exist
fileManager.setLocation(StandardLocation.CLASS_OUTPUT,
Arrays.asList(new File("d:\\compiledClasses")));
JavaCompiler.CompilationTask task = compiler.getTask(null,
fileManager, diagnostics, null, null, getCompilationUnits());
if (!task.call()) {
diagnostics.getDiagnostics().forEach(System.out::println);
}
fileManager.close();
//loading and using our compiled class
Class<ITest> test = (Class<ITest>) Class.forName("Test");
ITest iTest = test.newInstance();
iTest.doSomething();
But of course it doesn't change the running class path. It
will just compile the files in that folder. We still have to set our runtime path before running the app.
D:\compiling-string-example\target>java -cp
.;D:\compiledClasses;compiling-string-example-1.0-SNAPSHOT.jar
com.logicbig.example.StringCompilation
testing
|