1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| package javacompiler;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
public class Main {
public static void main(final String... args) {
final Optional<JavaCompiler> compilerOpt = Optional.ofNullable(ToolProvider.getSystemJavaCompiler());
compilerOpt.ifPresent(compiler -> {
try {
// Supported source version.
compiler.getSourceVersions().stream().forEach(System.out::println);
// Compile file.
final StringBuilder sourceCode = new StringBuilder();
sourceCode.append("public class SampleClass {\n")
.append(" public static void main(String[] args) {\n")
.append(" System.out.println( \"SampleClass has been compiled!\" );\n")
.append(" }\n")
.append("}");
final Path home = Files.createTempDirectory("Test-compiler");
final Path sourceFile = Paths.get(home.toString(), "SampleClass.java");
Files.write(sourceFile, Arrays.asList(sourceCode.toString()));
final DiagnosticCollector< JavaFileObject> diagnostics = new DiagnosticCollector<>();
final StandardJavaFileManager manager = compiler.getStandardFileManager(diagnostics, null, null);
final Iterable< ? extends JavaFileObject> sources = manager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile.toFile()));
final CompilationTask task = compiler.getTask(null, manager, diagnostics, null, null, sources);
task.call();
if (diagnostics.getDiagnostics().isEmpty()) {
final URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
final Class sysclass = URLClassLoader.class;
final Method addUrlMethod = sysclass.getDeclaredMethod("addURL", URL.class);
addUrlMethod.setAccessible(true);
addUrlMethod.invoke(sysloader, new Object[]{home.toUri().toURL()});
final Class aClass = Class.forName("SampleClass");
final Method mainMethod = aClass.getMethod("main", String[].class);
mainMethod.invoke(null, new Object[]{new String[0]}); // Issue when using varargs.
} else {
System.err.println("Compilation failed");
diagnostics.getDiagnostics()
.stream()
.forEach(diagnostic -> {
System.out.format("%s, line %d in %s",
diagnostic.getMessage(null),
diagnostic.getLineNumber(),
diagnostic.getSource().getName());
});
}
} catch (IOException | ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
});
}
} |
Partager