javax.annotation.processing.AbstractProcessor#javax.tools.ToolProvider源码实例Demo

下面列出了javax.annotation.processing.AbstractProcessor#javax.tools.ToolProvider 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Box   文件: DynamicCompiler.java
public boolean compile() {
	JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
	if (compiler == null) {
		LOG.error("Can not find compiler, please use JDK instead");
		return false;
	}
	fileManager = new ClassFileManager(compiler.getStandardFileManager(null, null, null));

	List<JavaFileObject> jFiles = new ArrayList<>(clsNodeList.size());
	for (ClassNode clsNode : clsNodeList) {
		jFiles.add(new CharSequenceJavaFileObject(clsNode.getFullName(), clsNode.getCode().toString()));
	}

	CompilationTask compilerTask = compiler.getTask(null, fileManager, null, null, null, jFiles);
	return Boolean.TRUE.equals(compilerTask.call());
}
 
源代码2 项目: grpc-nebula-java   文件: SimpleServiceTest.java
@Test
public void testRpcMethodAnnotations() throws Exception {
  File grpcJavaFile =
      new File("./src/generated/main/grpc/io/grpc/testing/protobuf/SimpleServiceGrpc.java");
  Assume.assumeTrue(grpcJavaFile.exists());

  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
  AnnotationProcessor processor = new AnnotationProcessor();
  Iterable<? extends JavaFileObject> obs = fileManager.getJavaFileObjects(grpcJavaFile);

  CompilationTask task =
      compiler.getTask(
          null,
          fileManager,
          null,
          Collections.singleton("-proc:only"),
          Collections.singleton(SimpleServiceGrpc.class.getCanonicalName()),
          obs);
  task.setProcessors(Collections.singleton(processor));
  assertTrue(task.call());
  assertTrue(processor.processedClass);
  fileManager.close();
}
 
public static void main(String[] args) throws Exception {
    String SCRATCH_DIR = System.getProperty("user.dir");
    JavaCompiler javacTool = ToolProvider.getSystemJavaCompiler();
    int n = 0;
    for (VersionKind versionKind : VersionKind.values()) {
        for (HierarchyKind hierarchyKind : HierarchyKind.values()) {
            for (TestKind testKind : TestKind.values()) {
                for (ActionKind actionKind : ActionKind.values()) {
                    File testDir = new File(SCRATCH_DIR, "test"+n);
                    new EagerInterfaceCompletionTest(javacTool, testDir, versionKind,
                            hierarchyKind, testKind, actionKind).test();
                    n++;
                }
            }
        }
    }
    if (nerrors > 0) {
        throw new AssertionError("Some errors have been detected");
    }
}
 
源代码4 项目: TencentKona-8   文件: DetectMutableStaticFields.java
void analyzeResource(URI resource)
    throws
        IOException,
        ConstantPoolException,
        InvalidDescriptor {
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    JavaFileManager.Location location =
            StandardLocation.locationFor(resource.getPath());
    fm.setLocation(location, com.sun.tools.javac.util.List.of(
            new File(resource.getPath())));

    for (JavaFileObject file : fm.list(location, "", EnumSet.of(CLASS), true)) {
        String className = fm.inferBinaryName(location, file);
        int index = className.lastIndexOf('.');
        String pckName = index == -1 ? "" : className.substring(0, index);
        if (shouldAnalyzePackage(pckName)) {
            analyzeClassFile(ClassFile.read(file.openInputStream()));
        }
    }
}
 
源代码5 项目: PacketProxy   文件: PPContextMenuManager.java
private void loadItems() throws Exception {
	module_list = new ArrayList<PPContextMenu>();
	JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
	JavaFileManager fm = compiler.getStandardFileManager(new DiagnosticCollector<JavaFileObject>(), null, null);

	Set<JavaFileObject.Kind> kind = Sets.newHashSet(JavaFileObject.Kind.CLASS);
	for (JavaFileObject f : fm.list(StandardLocation.CLASS_PATH, item_package, kind, false)) {
		Path item_file_path = Paths.get(f.getName());
		Path item_file_name = item_file_path.getFileName();
		String item_class_path = item_package + "." + item_file_name.toString().replaceAll("\\.class.*$", "");

           @SuppressWarnings("rawtypes")
		Class klass = Class.forName(item_class_path);
		if(item_class.isAssignableFrom(klass) && !Modifier.isAbstract(klass.getModifiers())){
               @SuppressWarnings("unchecked")
			PPContextMenu ppcm = createInstance(klass);	
			module_list.add(ppcm);
		}
	}
}
 
源代码6 项目: dragonwell8_jdk   文件: JGroupMain.java
private String generateInitScript() throws IOException {
    // load script content
    ClassLoader loader = ToolProvider.getSystemToolClassLoader(); // JGroupInitializer.sh is in jdk/lib/tools.jar
    InputStream stream = loader.getResourceAsStream(INITIALIZER_NAME);

    if (stream == null) {
        throw new IOException("Cannot load " + INITIALIZER_NAME + " using system classloader");
    }

    File script = File.createTempFile(SCRIPT_PREFIX, ".sh");
    script.setExecutable(true);
    script.setWritable(true);
    script.deleteOnExit();

    // copy content of initializer resource to a temp shell script file
    OutputStream fos = new FileOutputStream(script);
    int buf = 0;
    while ((buf = stream.read()) != -1) {
        fos.write(buf);
    }
    fos.close();

    return script.getAbsolutePath();
}
 
void run() throws Exception {
    JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
    JavaSource source = new JavaSource();
    JavacTask ct = (JavacTask)comp.getTask(null, null, null,
            null, null, Arrays.asList(source));
    try {
        if (!ct.call()) {
            throw new AssertionError(errorMessage +
                    source.getCharContent(true));
        }
    } catch (Throwable ex) {
        throw new AssertionError(errorMessage +
                source.getCharContent(true));
    }
    check();
}
 
源代码8 项目: TencentKona-8   文件: TestBootNativeLibraryPath.java
static void createTestClass() throws IOException {
    FileOutputStream fos = new FileOutputStream(TESTFILE + ".java");
    PrintStream ps = new PrintStream(fos);
    ps.println("public class " + TESTFILE + "{");
    ps.println("public static void main(String[] args) {\n");
    ps.println("System.out.println(System.getProperty(\"sun.boot.library.path\"));\n");
    ps.println("}}\n");
    ps.close();
    fos.close();

    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    String javacOpts[] = {TESTFILE + ".java"};
    if (javac.run(null, null, null,  javacOpts) != 0) {
        throw new RuntimeException("compilation of " + TESTFILE + ".java Failed");
    }
}
 
源代码9 项目: TencentKona-8   文件: T6395981.java
public static void main(String... args) {
    Tool compiler = ToolProvider.getSystemJavaCompiler();
    Set<SourceVersion> expected = EnumSet.noneOf(SourceVersion.class);
    for (String arg : args)
        expected.add(SourceVersion.valueOf(arg));
    Set<SourceVersion> found = compiler.getSourceVersions();
    Set<SourceVersion> notExpected = EnumSet.copyOf(found);
    for (SourceVersion version : expected) {
        if (!found.contains(version))
            throw new AssertionError("Expected source version not found: " + version);
        else
            notExpected.remove(version);
    }
    if (!notExpected.isEmpty())
        throw new AssertionError("Unexpected source versions: " + notExpected);
}
 
源代码10 项目: TencentKona-8   文件: JavacTemplateTestBase.java
private File compile(List<File> classpaths, List<JavaFileObject> files, boolean generate) throws IOException {
    JavaCompiler systemJavaCompiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = systemJavaCompiler.getStandardFileManager(null, null, null);
    if (classpaths.size() > 0)
        fm.setLocation(StandardLocation.CLASS_PATH, classpaths);
    JavacTask ct = (JavacTask) systemJavaCompiler.getTask(null, fm, diags, compileOptions, null, files);
    if (generate) {
        File destDir = new File(root, Integer.toString(counter.incrementAndGet()));
        // @@@ Assert that this directory didn't exist, or start counter at max+1
        destDir.mkdirs();
        fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir));
        ct.generate();
        return destDir;
    }
    else {
        ct.analyze();
        return nullDir;
    }
}
 
源代码11 项目: TencentKona-8   文件: GetTask_FileObjectsTest.java
/**
 * Verify that expected output files are written via the file manager,
 * for a source file read from the file system with StandardJavaFileManager.
 */
@Test
public void testStandardFileObject() throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File srcFile = new File(testSrc, "pkg/C.java");
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    File outDir = getOutDir();
    fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
    Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(srcFile);
    DocumentationTask t = tool.getTask(null, fm, null, null, null, files);
    if (t.call()) {
        System.err.println("task succeeded");
        checkFiles(outDir, standardExpectFiles);
    } else {
        throw new Exception("task failed");
    }
}
 
源代码12 项目: TencentKona-8   文件: BadClassfile.java
private static void test(String classname, String expected) throws Exception {
    File classfile = new File(System.getProperty("test.classes", "."), classname + ".class");
    ClassFile cf = ClassFile.read(classfile);

    cf = new ClassFile(cf.magic, Target.JDK1_7.minorVersion,
             Target.JDK1_7.majorVersion, cf.constant_pool, cf.access_flags,
            cf.this_class, cf.super_class, cf.interfaces, cf.fields,
            cf.methods, cf.attributes);

    new ClassWriter().write(cf, classfile);

    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    JavacTaskImpl task = (JavacTaskImpl) c.getTask(null, null, null, Arrays.asList("-classpath", System.getProperty("test.classes", ".")), null, null);

    try {
        Symbol clazz = com.sun.tools.javac.main.JavaCompiler.instance(task.getContext()).resolveIdent(classname);

        clazz.complete();
    } catch (BadClassFile f) {
        JCDiagnostic embeddedDiag = (JCDiagnostic) f.diag.getArgs()[1];
        assertEquals(expected, embeddedDiag.getCode());
        assertEquals(Integer.toString(Target.JDK1_7.majorVersion), embeddedDiag.getArgs()[0]);
        assertEquals(Integer.toString(Target.JDK1_7.minorVersion), embeddedDiag.getArgs()[1]);
    }
}
 
源代码13 项目: TencentKona-8   文件: GetTask_FileObjectsTest.java
/**
 * Verify bad file object is handled correctly.
 */
@Test
public void testBadFileObject() throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File srcFile = new File(testSrc, "pkg/C.class");  // unacceptable file kind
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    File outDir = getOutDir();
    fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
    Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(srcFile);
    try {
        DocumentationTask t = tool.getTask(null, fm, null, null, null, files);
        error("getTask succeeded, no exception thrown");
    } catch (IllegalArgumentException e) {
        System.err.println("exception caught as expected: " + e);
    }
}
 
源代码14 项目: TencentKona-8   文件: GetTask_OptionsTest.java
/**
 * Verify null is handled correctly.
 */
@Test
public void testNull() throws Exception {
    JavaFileObject srcFile = createSimpleJavaFileObject();
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    File outDir = getOutDir();
    fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
    Iterable<String> options = Arrays.asList((String) null);
    Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile);
    try {
        DocumentationTask t = tool.getTask(null, fm, null, null, options, files);
        error("getTask succeeded, no exception thrown");
    } catch (NullPointerException e) {
        System.err.println("exception caught as expected: " + e);
    }
}
 
源代码15 项目: TencentKona-8   文件: GetTask_DocletClassTest.java
/**
 * Verify that an alternate doclet can be specified.
 *
 * There is no standard interface or superclass for a doclet;
 * the only requirement is that it provides static methods that
 * can be invoked via reflection. So, for now, the doclet is
 * specified as a class.
 * Because we cannot create and use a unique instance of the class,
 * we verify that the doclet has been called by having it record
 * (in a static field!) the comment from the last time it was invoked,
 * which is randomly generated each time the test is run.
 */
@Test
public void testDoclet() throws Exception {
    Random r = new Random();
    int key = r.nextInt();
    JavaFileObject srcFile = createSimpleJavaFileObject(
            "pkg/C",
            "package pkg; /** " + key + "*/ public class C { }");
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    File outDir = getOutDir();
    fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
    Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile);
    DocumentationTask t = tool.getTask(null, fm, null, TestDoclet.class, null, files);
    if (t.call()) {
        System.err.println("task succeeded");
        if (TestDoclet.lastCaller.equals(String.valueOf(key)))
            System.err.println("found expected key: " + key);
        else
            error("Expected key not found");
        checkFiles(outDir, Collections.<String>emptySet());
    } else {
        throw new Exception("task failed");
    }
}
 
源代码16 项目: TencentKona-8   文件: GetTask_DocletClassTest.java
/**
 * Verify that exceptions from a doclet are thrown as expected.
 */
@Test
public void testBadDoclet() throws Exception {
    JavaFileObject srcFile = createSimpleJavaFileObject();
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    File outDir = getOutDir();
    fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
    Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile);
    DocumentationTask t = tool.getTask(null, fm, null, BadDoclet.class, null, files);
    try {
        t.call();
        error("call completed without exception");
    } catch (RuntimeException e) {
        Throwable c = e.getCause();
        if (c.getClass() == UnexpectedError.class)
            System.err.println("exception caught as expected: " + c);
        else
            throw e;
    }
}
 
源代码17 项目: TencentKona-8   文件: GetTask_FileManagerTest.java
/**
 * Verify that an alternate file manager can be specified:
 * in this case, a PathFileManager.
 */
@Test
public void testFileManager() throws Exception {
    JavaFileObject srcFile = createSimpleJavaFileObject();
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    PathFileManager fm = new JavacPathFileManager(new Context(), false, null);
    Path outDir = getOutDir().toPath();
    fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
    Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile);
    DocumentationTask t = tool.getTask(null, fm, null, null, null, files);
    if (t.call()) {
        System.err.println("task succeeded");
        checkFiles(outDir, standardExpectFiles);
    } else {
        throw new Exception("task failed");
    }
}
 
void run() throws Exception {
    JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
    File classesDir = new File(System.getProperty("user.dir"), "classes");
    classesDir.mkdirs();
    JavaSource[] sources = new JavaSource[]{
        new JavaSource("TestOneIgnorableChar", "AA\\u0000BB"),
        new JavaSource("TestMultipleIgnorableChar", "AA\\u0000\\u0000\\u0000BB")};
    JavacTask ct = (JavacTask)comp.getTask(null, null, null,
            Arrays.asList("-d", classesDir.getPath()),
            null, Arrays.asList(sources));
    try {
        if (!ct.call()) {
            throw new AssertionError("Error thrown when compiling test cases");
        }
    } catch (Throwable ex) {
        throw new AssertionError("Error thrown when compiling test cases");
    }
    check(classesDir,
            "TestOneIgnorableChar.class",
            "TestOneIgnorableChar$AABB.class",
            "TestMultipleIgnorableChar.class",
            "TestMultipleIgnorableChar$AABB.class");
    if (errors > 0)
        throw new AssertionError("There are some errors in the test check the error output");
}
 
源代码19 项目: TencentKona-8   文件: GetTask_WriterTest.java
/**
 * Verify that a writer can be provided.
 */
@Test
public void testWriter() throws Exception {
    JavaFileObject srcFile = createSimpleJavaFileObject();
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    File outDir = getOutDir();
    fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
    Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile);
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    DocumentationTask t = tool.getTask(pw, fm, null, null, null, files);
    if (t.call()) {
        System.err.println("task succeeded");
        checkFiles(outDir, standardExpectFiles);
        String out = sw.toString();
        System.err.println(">>" + out + "<<");
        for (String f: standardExpectFiles) {
            String f1 = f.replace('/', File.separatorChar);
            if (f1.endsWith(".html") && !out.contains(f1))
                throw new Exception("expected string not found: " + f1);
        }
    } else {
        throw new Exception("task failed");
    }
}
 
源代码20 项目: TencentKona-8   文件: BadLambdaExpr.java
public static void main(String... args) throws Exception {

        //create default shared JavaCompiler - reused across multiple compilations
        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);

        for (ParameterListKind plk : ParameterListKind.values()) {
            for (ParameterKind pk : ParameterKind.values()) {
                for (ArrowKind ak : ArrowKind.values()) {
                    for (ExprKind ek : ExprKind.values()) {
                        new BadLambdaExpr(plk, pk, ak, ek).run(comp, fm);
                    }
                }
            }
        }
        System.out.println("Total check executed: " + checkCount);
    }
 
源代码21 项目: TencentKona-8   文件: DuplicateConstantPoolEntry.java
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");
        }
    }
 
源代码22 项目: TencentKona-8   文件: TestCompileJARInClassPath.java
void compileWithJSR199() throws IOException {
    String cpath = "C2.jar";
    File clientJarFile = new File(cpath);
    File sourceFileToCompile = new File("C3.java");


    javax.tools.JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    StandardJavaFileManager stdFileManager = javac.getStandardFileManager(diagnostics, null, null);

    List<File> files = new ArrayList<>();
    files.add(clientJarFile);

    stdFileManager.setLocation(StandardLocation.CLASS_PATH, files);

    Iterable<? extends JavaFileObject> sourceFiles = stdFileManager.getJavaFileObjects(sourceFileToCompile);

    if (!javac.getTask(null, stdFileManager, diagnostics, null, null, sourceFiles).call()) {
        throw new AssertionError("compilation failed");
    }
}
 
源代码23 项目: TencentKona-8   文件: TestDefaultMethodsSyntax.java
public static void main(String... args) throws Exception {

        //create default shared JavaCompiler - reused across multiple compilations
        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);

        for (VersionKind vk : VersionKind.values()) {
            for (EnclosingKind ek : EnclosingKind.values()) {
                for (MethodKind mk : MethodKind.values()) {
                    for (ModifierKind modk1 : ModifierKind.values()) {
                        for (ModifierKind modk2 : ModifierKind.values()) {
                            new TestDefaultMethodsSyntax(vk, ek, mk, modk1, modk2).run(comp, fm);
                        }
                    }
                }
            }
        }
        System.out.println("Total check executed: " + checkCount);
    }
 
源代码24 项目: TencentKona-8   文件: T7068437.java
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());
}
 
源代码25 项目: TencentKona-8   文件: T7086601b.java
public static void main(String... args) throws Exception {

        //create default shared JavaCompiler - reused across multiple compilations
        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);

        for (TypeKind a1 : TypeKind.values()) {
            for (TypeKind a2 : TypeKind.values()) {
                for (TypeKind a3 : TypeKind.values()) {
                    for (MethodCallKind mck : MethodCallKind.values()) {
                        new T7086601b(a1, a2, a3, mck).run(comp, fm);
                    }
                }
            }
        }
        System.out.println("Total check executed: " + checkCount);
    }
 
public static void main(String... args) throws Exception {

        //create default shared JavaCompiler - reused across multiple compilations
        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);

        for (BoundKind boundKind : BoundKind.values()) {
            for (ConstructorKind constructorKind : ConstructorKind.values()) {
                for (TypeArgumentKind declArgKind : TypeArgumentKind.values()) {
                    for (TypeArgArity arity : TypeArgArity.values()) {
                        for (TypeArgumentKind useArgKind : TypeArgumentKind.values()) {
                            for (TypeArgumentKind diamondArgKind : TypeArgumentKind.values()) {
                                for (ArgumentKind argKind : ArgumentKind.values()) {
                                    new GenericConstructorAndDiamondTest(boundKind, constructorKind,
                                            declArgKind, arity, useArgKind, diamondArgKind, argKind).run(comp, fm);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
 
源代码27 项目: TencentKona-8   文件: T6557752.java
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!");
    }
}
 
源代码28 项目: TencentKona-8   文件: T6963934.java
public static void main(String[] args) throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File thisSrc = new File(testSrc, T6963934.class.getSimpleName() + ".java");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    JavacTask task = (JavacTask) compiler.getTask(null, fileManager, null, null, null,
            fileManager.getJavaFileObjects(thisSrc));
    CompilationUnitTree tree = task.parse().iterator().next();
    int count = 0;
    for (ImportTree importTree : tree.getImports()) {
        System.out.println(importTree);
        count++;
    }
    int expected = 7;
    if (count != expected)
        throw new Exception("unexpected number of imports found: " + count + ", expected: " + expected);
}
 
源代码29 项目: TencentKona-8   文件: Warn4.java
@Override
public void run() {
    int id = checkCount.incrementAndGet();
    final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavaSource source = new JavaSource(id);
    JavacTask ct = (JavacTask)tool.getTask(null, fm.get(), diagChecker,
            Arrays.asList("-Xlint:unchecked", "-source", sourceLevel.sourceKey),
            null, Arrays.asList(source));
    ct.call(); //to get mandatory notes
    check(source, new boolean[] {vararg_meth.giveUnchecked(client_meth),
                           vararg_meth.giveVarargs(client_meth)});
}
 
源代码30 项目: chaosblade-exec-jvm   文件: JavaCodeScriptEngine.java
private Class compileClass(ClassLoader classLoader, String className, String scriptId, String content) {
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    if (javaCompiler == null) {
        throw new ScriptException("Not found system java compile");
    }
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    JavaFileObject javaFileObject = new InputStringJavaFileObject(className, content);
    StandardJavaFileManager standardFileManager = javaCompiler.getStandardFileManager(null, null, CHARSET_UTF8);
    InMemoryJavaFileManager fileManager = new InMemoryJavaFileManager(classLoader, standardFileManager);
    JavaCompiler.CompilationTask compilationTask = javaCompiler.getTask(null, fileManager, diagnostics, null, null,
        Arrays.asList(javaFileObject));
    if (Boolean.TRUE.equals(compilationTask.call())) {
        try {
            return new CompiledClassLoader(classLoader, fileManager.getOutputs()).loadClass(className);
        } catch (Exception ce) {
            throw convertToScriptException("compile class failed:" + className, scriptId, ce);
        }
    } else {
        StringBuilder reporter = new StringBuilder(1024);
        reporter.append("Compilation failed.\n");
        try {
            generateDiagnosticReport(diagnostics, reporter);
        } catch (IOException e) {
            reporter.append("io exception:" + e.getMessage());
        }
        throw new ScriptException(reporter.toString());
    }
}