Java Code Examples for javax.tools.JavaCompiler#getTask()
The following examples show how to use
javax.tools.JavaCompiler#getTask() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Abort.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
public static void main(String... args) throws Exception { String SCRATCH_DIR = System.getProperty("user.dir"); JavaCompiler javacTool = ToolProvider.getSystemJavaCompiler(); java.io.File testDir = new java.io.File(SCRATCH_DIR); sourceA.dumpTo(testDir); sourceB.dumpTo(testDir); DiagnosticChecker diagChecker = new DiagnosticChecker(); JavacTask ct = (JavacTask)javacTool.getTask(null, null, diagChecker, Arrays.asList("-XDrawDiagnostics", "-cp", testDir.getAbsolutePath()), null, Arrays.asList(sourceA.asJFO(testDir))); try { ct.analyze(); } catch (Throwable ex) { //ignore abort exception thrown by javac } if (!diagChecker.errorFound) { throw new AssertionError("Missing diagnostic"); } }
Example 2
Source File: T7068437.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
void run() throws Exception { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); System.err.println("using " + compiler.getClass() + " from " + compiler.getClass().getProtectionDomain().getCodeSource()); CompilationTask task = compiler.getTask(null, null, null, Collections.singleton("-proc:only"), Collections.singleton("java.lang.Object"), null); task.setProcessors(Collections.singleton(new Proc())); check("compilation", task.call()); task = compiler.getTask(null, null, null, Arrays.asList("-proc:only", "-AexpectFile"), Collections.singleton("java.lang.Object"), null); task.setProcessors(Collections.singleton(new Proc())); check("compilation", task.call()); }
Example 3
Source File: Main.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws IOException { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); JavacTask task = (JavacTask) compiler.getTask(null, null, null, null, null, List.of(new MyFileObject())); trees = Trees.instance(task); Iterable<? extends CompilationUnitTree> asts = task.parse(); task.analyze(); for (CompilationUnitTree ast : asts) { new MyVisitor().scan(ast, null); } }
Example 4
Source File: T6557752.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws IOException { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); task = (JavacTask) compiler.getTask(null, null, null, null, null, List.of(new MyFileObject())); Iterable<? extends CompilationUnitTree> asts = task.parse(); task.analyze(); trees = Trees.instance(task); MyVisitor myVisitor = new MyVisitor(); for (CompilationUnitTree ast : asts) { myVisitor.compilationUnit = ast; myVisitor.scan(ast, null); } if (!myVisitor.foundError) { throw new AssertionError("Expected error not found!"); } }
Example 5
Source File: DuplicateConstantPoolEntry.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
void generateFilesNeeded() throws Exception { StringJavaFileObject[] CSource = new StringJavaFileObject[] { new StringJavaFileObject("C.java", "class C {C(String s) {}}"), }; List<StringJavaFileObject> AandBSource = Arrays.asList( new StringJavaFileObject("A.java", "class A {void test() {new B(null);new C(null);}}"), new StringJavaFileObject("B.java", "class B {B(String s) {}}") ); final JavaCompiler tool = ToolProvider.getSystemJavaCompiler(); JavacTask compileC = (JavacTask)tool.getTask(null, null, null, null, null, Arrays.asList(CSource)); if (!compileC.call()) { throw new AssertionError("Compilation error while compiling C.java sources"); } JavacTask compileAB = (JavacTask)tool.getTask(null, null, null, Arrays.asList("-cp", "."), null, AandBSource); if (!compileAB.call()) { throw new AssertionError("Compilation error while compiling A and B sources"); } }
Example 6
Source File: FunctionalInterfaceConversionTest.java From jdk8u60 with GNU General Public License v2.0 | 6 votes |
@Override public void run() { final JavaCompiler tool = ToolProvider.getSystemJavaCompiler(); JavacTask ct = (JavacTask)tool.getTask(null, fm.get(), dc, null, null, Arrays.asList(samSourceFile, pkgClassSourceFile, clientSourceFile)); try { ct.analyze(); } catch (IOException ex) { throw new AssertionError("Test failing with cause", ex.getCause()); } if (dc.errorFound == checkSamConversion()) { throw new AssertionError(samSourceFile + "\n\n" + pkgClassSourceFile + "\n\n" + clientSourceFile); } }
Example 7
Source File: SchemaGenerator.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
public static boolean compile(String[] args, File episode) throws Exception { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null); JavacOptions options = JavacOptions.parse(compiler, fileManager, args); List<String> unrecognizedOptions = options.getUnrecognizedOptions(); if (!unrecognizedOptions.isEmpty()) Logger.getLogger(SchemaGenerator.class.getName()).log(Level.WARNING, "Unrecognized options found: {0}", unrecognizedOptions); Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(options.getFiles()); JavaCompiler.CompilationTask task = compiler.getTask( null, fileManager, diagnostics, options.getRecognizedOptions(), options.getClassNames(), compilationUnits); com.sun.tools.internal.jxc.ap.SchemaGenerator r = new com.sun.tools.internal.jxc.ap.SchemaGenerator(); if (episode != null) r.setEpisodeFile(episode); task.setProcessors(Collections.singleton(r)); boolean res = task.call(); //Print messages generated by compiler for (Diagnostic<? extends JavaFileObject> d : diagnostics.getDiagnostics()) { System.err.println(d.toString()); } return res; }
Example 8
Source File: InterfaceMethodHidingTest.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception { JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker, Arrays.asList("-XDallowStaticInterfaceMethods"), null, Arrays.asList(source)); try { ct.analyze(); } catch (Throwable ex) { throw new AssertionError("Error thrown when analyzing the following source:\n" + source.getCharContent(true)); } check(); }
Example 9
Source File: Main.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws IOException { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); JavacTask task = (JavacTask) compiler.getTask(null, null, null, null, null, List.of(new MyFileObject())); trees = Trees.instance(task); Iterable<? extends CompilationUnitTree> asts = task.parse(); task.analyze(); for (CompilationUnitTree ast : asts) { new MyVisitor().scan(ast, null); } }
Example 10
Source File: CompilerUtils.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
/** * Compile all the java sources in {@code <source>} and optionally its * subdirectories, to * {@code <destination>}. The destination directory will be created if * it doesn't exist. * * All warnings/errors emitted by the compiler are output to System.out/err. * * @param source Path to the source directory * @param destination Path to the destination directory * @param recurse If {@code true} recurse into any {@code source} subdirectories * to compile all java source files; else only compile those directly in * {@code source}. * @param options Any options to pass to the compiler * * @return true if the compilation is successful * * @throws IOException * if there is an I/O error scanning the source tree or * creating the destination directory * @throws UnsupportedOperationException * if there is no system java compiler */ public static boolean compile(Path source, Path destination, boolean recurse, String... options) throws IOException { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if (compiler == null) { // no compiler available throw new UnsupportedOperationException("Unable to get system java compiler. " + "Perhaps, jdk.compiler module is not available."); } StandardJavaFileManager jfm = compiler.getStandardFileManager(null, null, null); List<Path> sources = Files.find(source, (recurse ? Integer.MAX_VALUE : 1), (file, attrs) -> (file.toString().endsWith(".java"))) .collect(Collectors.toList()); Files.createDirectories(destination); jfm.setLocation(StandardLocation.CLASS_PATH, Collections.emptyList()); jfm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT, Collections.singletonList(destination)); List<String> opts = Arrays.asList(options); JavaCompiler.CompilationTask task = compiler.getTask(null, jfm, null, opts, null, jfm.getJavaFileObjectsFromPaths(sources)); return task.call(); }
Example 11
Source File: TestGetScope.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
public void run() { File srcDir = new File(System.getProperty("test.src")); File thisFile = new File(srcDir, getClass().getName() + ".java"); JavaCompiler c = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fm = c.getStandardFileManager(null, null, null); List<String> opts = Arrays.asList("-proc:only", "-doe"); Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(thisFile); JavacTask t = (JavacTask) c.getTask(null, fm, null, opts, null, files); t.setProcessors(Collections.singleton(this)); boolean ok = t.call(); if (!ok) throw new Error("compilation failed"); }
Example 12
Source File: TruffleJsonFunctionWrapperGeneratorTest.java From client-sdk-java with Apache License 2.0 | 5 votes |
private static void verifyGeneratedCode(String sourceFile) throws IOException { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>(); try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null)) { Iterable<? extends JavaFileObject> compilationUnits = fileManager .getJavaFileObjectsFromStrings(Collections.singletonList(sourceFile)); JavaCompiler.CompilationTask task = compiler.getTask( null, fileManager, diagnostics, null, null, compilationUnits); assertTrue("Generated contract contains compile time error", task.call()); } }
Example 13
Source File: ImplementationCacheTest.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws IOException { List<? extends JavaFileObject> files = Arrays.asList(new SourceFile()); JavaCompiler tool = ToolProvider.getSystemJavaCompiler(); JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, files); Context ctx = new Context(); JavacFileManager.preRegister(ctx); checkImplementationCache(ct.analyze(), Types.instance(ctx)); }
Example 14
Source File: IntersectionTypeCastTest.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
@Override public void run() { final JavaCompiler tool = ToolProvider.getSystemJavaCompiler(); JavacTask ct = (JavacTask)tool.getTask(null, fm.get(), diagChecker, null, null, Arrays.asList(source)); try { ct.analyze(); } catch (Throwable ex) { throw new AssertionError("Error thrown when compiling the following code:\n" + source.getCharContent(true)); } check(); }
Example 15
Source File: BadLambdaExpr.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception { JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker, null, null, Arrays.asList(source)); try { ct.parse(); } catch (Throwable ex) { throw new AssertionError("Error thron when parsing the following source:\n" + source.getCharContent(true)); } check(); }
Example 16
Source File: Main.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws IOException { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); JavacTask task = (JavacTask) compiler.getTask(null, null, null, null, null, List.of(new MyFileObject())); trees = Trees.instance(task); Iterable<? extends CompilationUnitTree> asts = task.parse(); task.analyze(); for (CompilationUnitTree ast : asts) { new MyVisitor().scan(ast, null); } }
Example 17
Source File: GenericConstructorAndDiamondTest.java From jdk8u60 with GNU General Public License v2.0 | 4 votes |
void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception { JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker, null, null, Arrays.asList(source)); ct.analyze(); check(); }
Example 18
Source File: InterruptedExceptionTest.java From TencentKona-8 with GNU General Public License v2.0 | 4 votes |
void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception { JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker, Arrays.asList(xlint.getXlintOption()), null, Arrays.asList(source)); ct.analyze(); check(); }
Example 19
Source File: SortMethodsTest.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 4 votes |
public static void main(String args[]) { JavaCompiler comp = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diags = new DiagnosticCollector<JavaFileObject>(); final String cName = new String("ManyMethodsClass"); Vector<Long> results = new Vector<Long>(); for (int i = 6; i < 600000; i*=10) { String klass = createClass(cName, i); JavaMemoryFileObject file = new JavaMemoryFileObject(cName, klass); MemoryFileManager mfm = new MemoryFileManager(comp.getStandardFileManager(diags, null, null), file); CompilationTask task = comp.getTask(null, mfm, diags, null, null, Arrays.asList(file)); if (task.call()) { try { MemoryClassLoader mcl = new MemoryClassLoader(file); long start = System.nanoTime(); Class<? extends Object> c = Class.forName(cName, true, mcl); long end = System.nanoTime(); results.add(end - start); Method m = c.getDeclaredMethod("sayHello", new Class[0]); String ret = (String)m.invoke(null, new Object[0]); System.out.println(ret + " (loaded and resloved in " + (end - start) + "ns)"); } catch (Exception e) { System.err.println(e); } } else { System.out.println(klass); System.out.println(); for (Diagnostic diag : diags.getDiagnostics()) { System.out.println(diag.getCode() + "\n" + diag.getKind() + "\n" + diag.getPosition()); System.out.println(diag.getSource() + "\n" + diag.getMessage(null)); } } } long lastRatio = 0; for (int i = 2; i < results.size(); i++) { long normalized1 = Math.max(results.get(i-1) - results.get(0), 1); long normalized2 = Math.max(results.get(i) - results.get(0), 1); long ratio = normalized2/normalized1; lastRatio = ratio; System.out.println("10 x more methods requires " + ratio + " x more time"); } // The following is just vague estimation but seems to work on current x86_64 and sparcv9 machines if (lastRatio > 80) { throw new RuntimeException("ATTENTION: it seems that class loading needs quadratic time with regard to the number of class methods!!!"); } }
Example 20
Source File: QueryBeforeEnter.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
@Test public void testTooSoon(Path base) throws Exception { Path src = base.resolve("src"); tb.writeJavaFiles(src, "package test; public class Test {}"); Path out = base.resolve("out"); Files.createDirectories(out); Path reg = base.resolve("reg"); Path regFile = reg.resolve("META-INF").resolve("services").resolve(Plugin.class.getName()); Files.createDirectories(regFile.getParent()); try (OutputStream regOut = Files.newOutputStream(regFile)) { regOut.write(PluginImpl.class.getName().getBytes()); } String processorPath = System.getProperty("test.class.path") + File.pathSeparator + reg.toString(); JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler(); Path testSource = src.resolve("test").resolve("Test.java"); try (StandardJavaFileManager fm = javaCompiler.getStandardFileManager(null, null, null)) { com.sun.source.util.JavacTask task = (com.sun.source.util.JavacTask) javaCompiler.getTask(null, null, d -> { throw new IllegalStateException(d.toString()); }, Arrays.asList("--processor-path", processorPath, "-processor", AP.class.getName(), "-Xplugin:test"), null, fm.getJavaFileObjects(testSource)); task.call(); } Main.compile(new String[] {"--processor-path", processorPath, "-Xplugin:test", testSource.toString()}); }