How to compile a .java file from a java program

Possible duplicate:
Compiling external .java files from Java

I use examples from all over the network, but I keep getting NullPointerExceptions when calling the run method in JavaCompiler. If you know how to compile another java file from a java file, specify the code on how to do it. Thanks

-1
source share
3 answers

I have already used JavaCompiler to compile mathematical expressions on the fly.

Here is how I did it:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null); Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromStrings(Arrays.asList("YouFileToCompile.java")); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits); boolean success = task.call(); fileManager.close(); 
+3
source

From the documentation for STBC (which uses JavaCompiler ).

The docs for getSystemJavaCompiler() mention that it returns "the compiler that comes with this platform, or null if the compiler is not provided," but does not specify why it might be null , and the fact that the compiler will not be available for applets or web start applications ...

This will be null if the code runs in a non-SDK JRE (see explanation in System Requirements ).

+1
source

You can use the eclipse jdt compiler ( http://www.eclipse.org/jdt/core ). It is used in many projects to compile java.

Here is an example of how tomcat uses it to compile servlets in .class: http://www.docjar.com/html/api/org/apache/jasper/compiler/JDTCompiler.java.html

0
source

Source: https://habr.com/ru/post/972307/


All Articles