当前位置: 首页>>代码示例>>Java>>正文


Java DiagnosticCollector类代码示例

本文整理汇总了Java中javax.tools.DiagnosticCollector的典型用法代码示例。如果您正苦于以下问题:Java DiagnosticCollector类的具体用法?Java DiagnosticCollector怎么用?Java DiagnosticCollector使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


DiagnosticCollector类属于javax.tools包,在下文中一共展示了DiagnosticCollector类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: compileClass

import javax.tools.DiagnosticCollector; //导入依赖的package包/类
/**
 * Compile the provided class. The className may have a package separated by /. For example:
 * my/package/myclass
 * 
 * @param className Name of the class to compile.
 * @param classCode Plain text contents of the class
 * @return The byte contents of the compiled class.
 * @throws IOException
 */
public byte[] compileClass(final String className, final String classCode) throws IOException {
  ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

  JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
  OutputStreamJavaFileManager<JavaFileManager> fileManager =
      new OutputStreamJavaFileManager<JavaFileManager>(
          javaCompiler.getStandardFileManager(null, null, null), byteArrayOutputStream);

  List<JavaFileObject> fileObjects = new ArrayList<JavaFileObject>();
  fileObjects.add(new JavaSourceFromString(className, classCode));

  List<String> options = Arrays.asList("-classpath", this.classPath);
  DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
  if (!javaCompiler.getTask(null, fileManager, diagnostics, options, null, fileObjects).call()) {
    StringBuilder errorMsg = new StringBuilder();
    for (Diagnostic d : diagnostics.getDiagnostics()) {
      String err = String.format("Compilation error: Line %d - %s%n", d.getLineNumber(),
          d.getMessage(null));
      errorMsg.append(err);
      System.err.print(err);
    }
    throw new IOException(errorMsg.toString());
  }
  return byteArrayOutputStream.toByteArray();
}
 
开发者ID:ampool,项目名称:monarch,代码行数:35,代码来源:ClassBuilder.java

示例2: compile

import javax.tools.DiagnosticCollector; //导入依赖的package包/类
public synchronized Class compile(final String className, final CharSequence javaSource,
                                  final DiagnosticCollector<JavaFileObject> diagnosticsList)
                                                                                            throws JdkCompileException,
                                                                                            ClassCastException {
    if (diagnosticsList != null) {
        diagnostics = diagnosticsList;
    } else {
        diagnostics = new DiagnosticCollector<JavaFileObject>();
    }

    Map<String, CharSequence> classes = new HashMap<String, CharSequence>(1);
    classes.put(className, javaSource);

    Map<String, Class> compiled = compile(classes, diagnosticsList);
    Class newClass = compiled.get(className);
    return newClass;
}
 
开发者ID:luoyaogui,项目名称:otter-G,代码行数:18,代码来源:JdkCompileTask.java

示例3: compile

import javax.tools.DiagnosticCollector; //导入依赖的package包/类
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));
            return task.call();
        }
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:24,代码来源:SchemaGenerator.java

示例4: validateExpression

import javax.tools.DiagnosticCollector; //导入依赖的package包/类
/**
 * This method validates the given expression and updates the expression-editor's datasturcture accordingly
 * 
 * @param expressionText
 * @param inputFields
 * @param expressionEditorData
 */
public static void validateExpression(String expressionText,Map<String, Class<?>> inputFields,ExpressionEditorData expressionEditorData ) {
	if(BuildExpressionEditorDataSturcture.INSTANCE.getCurrentProject()!=null){
	DiagnosticCollector<JavaFileObject> diagnosticCollector = null;
	try {
		inputFields.putAll(expressionEditorData.getExtraFieldDatatypeMap());
		diagnosticCollector = ValidateExpressionToolButton
				.compileExpresion(expressionText,inputFields,expressionEditorData.getComponentName());
		if (diagnosticCollector != null && !diagnosticCollector.getDiagnostics().isEmpty()) {
			for (Diagnostic<?> diagnostic : diagnosticCollector.getDiagnostics()) {
				if (StringUtils.equals(diagnostic.getKind().name(), Diagnostic.Kind.ERROR.name())) {
					expressionEditorData.setValid(false);
					return;
				}
			}
		}
	} catch (JavaModelException | InvocationTargetException | ClassNotFoundException | MalformedURLException
			| IllegalAccessException | IllegalArgumentException e) {
		expressionEditorData.setValid(false);
		return;
	}
	expressionEditorData.setValid(true);
	}
}
 
开发者ID:capitalone,项目名称:Hydrograph,代码行数:31,代码来源:ExpressionEditorUtil.java

示例5: run

import javax.tools.DiagnosticCollector; //导入依赖的package包/类
private void run() {
    File classToCheck = new File(System.getProperty("test.classes"),
        getClass().getSimpleName() + ".class");

    DiagnosticCollector<JavaFileObject> dc =
            new DiagnosticCollector<JavaFileObject>();
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    JavaFileManager fm = JavapFileManager.create(dc, pw);
    JavapTask t = new JavapTask(pw, fm, dc, null,
            Arrays.asList(classToCheck.getPath()));
    if (t.run() != 0)
        throw new Error("javap failed unexpectedly");

    List<Diagnostic<? extends JavaFileObject>> diags = dc.getDiagnostics();
    for (Diagnostic<? extends JavaFileObject> d: diags) {
        if (d.getKind() == Diagnostic.Kind.ERROR)
            throw new AssertionError(d.getMessage(Locale.ENGLISH));
    }
    String lineSep = System.getProperty("line.separator");
    String out = sw.toString().replace(lineSep, "\n");
    if (!out.equals(expOutput)) {
        throw new AssertionError("The output is not equal to the one expected");
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:26,代码来源:JavapTaskCtorFailWithNPE.java

示例6: javap

import javax.tools.DiagnosticCollector; //导入依赖的package包/类
private String javap(List<String> args, List<String> classes) {
    DiagnosticCollector<JavaFileObject> dc = new DiagnosticCollector<JavaFileObject>();
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    JavaFileManager fm = JavapFileManager.create(dc, pw);
    JavapTask t = new JavapTask(pw, fm, dc, args, classes);
    if (t.run() != 0)
        throw new Error("javap failed unexpectedly");

    List<Diagnostic<? extends JavaFileObject>> diags = dc.getDiagnostics();
    for (Diagnostic<? extends JavaFileObject> d: diags) {
        if (d.getKind() == Diagnostic.Kind.ERROR)
            throw new Error(d.getMessage(Locale.ENGLISH));
    }
    return sw.toString();

}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:18,代码来源:T7190862.java

示例7: parse

import javax.tools.DiagnosticCollector; //导入依赖的package包/类
static List<? extends Tree> parse(String srcfile) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> fileObjects = fileManager.getJavaFileObjects(srcfile);
    String classPath = System.getProperty("java.class.path");
    List<String> options = Arrays.asList("-classpath", classPath);
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    Context context = new Context();
    JavacTaskImpl task = (JavacTaskImpl) ((JavacTool) compiler).getTask(null, null,
            diagnostics, options, null, fileObjects, context);
    TrialParserFactory.instance(context);
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    Iterator<? extends CompilationUnitTree> it = asts.iterator();
    if (it.hasNext()) {
        CompilationUnitTree cut = it.next();
        return cut.getTypeDecls();
    } else {
        throw new AssertionError("Expected compilation unit");
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:21,代码来源:JavacExtensionTest.java

示例8: testVariableInIfThen1

import javax.tools.DiagnosticCollector; //导入依赖的package包/类
@Test
void testVariableInIfThen1() throws IOException {

    String code = "package t; class Test { " +
            "private static void t(String name) { " +
            "if (name != null) String nn = name.trim(); } }";

    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen1",
            Arrays.<String>asList("compiler.err.variable.not.allowed"),
            codes);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:26,代码来源:JavacParserTest.java

示例9: testVariableInIfThen2

import javax.tools.DiagnosticCollector; //导入依赖的package包/类
@Test
void testVariableInIfThen2() throws IOException {

     String code = "package t; class Test { " +
             "private static void t(String name) { " +
             "if (name != null) class X {} } }";
     DiagnosticCollector<JavaFileObject> coll =
             new DiagnosticCollector<JavaFileObject>();
     JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
             null, Arrays.asList(new MyFileObject(code)));

     ct.parse();

     List<String> codes = new LinkedList<String>();

     for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
         codes.add(d.getCode());
     }

     assertEquals("testVariableInIfThen2",
             Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
 }
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:23,代码来源:JavacParserTest.java

示例10: testVariableInIfThen3

import javax.tools.DiagnosticCollector; //导入依赖的package包/类
@Test
void testVariableInIfThen3() throws IOException {

    String code = "package t; class Test { "+
            "private static void t() { " +
            "if (true) abstract class F {} }}";
    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();
    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen3",
            Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:23,代码来源:JavacParserTest.java

示例11: testVariableInIfThen4

import javax.tools.DiagnosticCollector; //导入依赖的package包/类
@Test
void testVariableInIfThen4() throws IOException {

    String code = "package t; class Test { "+
            "private static void t(String name) { " +
            "if (name != null) interface X {} } }";
    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();
    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen4",
            Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:23,代码来源:JavacParserTest.java

示例12: testVariableInIfThen5

import javax.tools.DiagnosticCollector; //导入依赖的package包/类
@Test
void testVariableInIfThen5() throws IOException {

    String code = "package t; class Test { "+
            "private static void t() { " +
            "if (true) } }";
    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();
    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen5",
            Arrays.<String>asList("compiler.err.illegal.start.of.stmt"),
            codes);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:24,代码来源:JavacParserTest.java

示例13: compileWithJSR199

import javax.tools.DiagnosticCollector; //导入依赖的package包/类
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<>();
    try (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");
        }
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:23,代码来源:TestCompileJARInClassPath.java

示例14: compile

import javax.tools.DiagnosticCollector; //导入依赖的package包/类
private <S> InMemoryFileManager compile(
        List<String> options,
        Function<S, ? extends JavaFileObject> src2JavaFileObject,
        List<S> sources)
        throws IOException, CompilationException {

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    List<? extends JavaFileObject> src = sources.stream()
            .map(src2JavaFileObject)
            .collect(Collectors.toList());

    DiagnosticCollector<? super JavaFileObject> dc = new DiagnosticCollector<>();
    try (InMemoryFileManager fileManager
                 = new InMemoryFileManager(compiler.getStandardFileManager(null, null, null))) {
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, dc, options, null, src);
        boolean success = task.call();
        if (!success) {
            String errorMessage = dc.getDiagnostics().stream()
                    .map(Object::toString)
                    .collect(Collectors.joining("\n"));
            throw new CompilationException("Compilation Error\n\n" + errorMessage);
        }
        return fileManager;
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:26,代码来源:TestBase.java

示例15: getCompileResult

import javax.tools.DiagnosticCollector; //导入依赖的package包/类
private boolean getCompileResult(String contents, String className,
        boolean shouldCompile) throws Exception{

    DiagnosticCollector<JavaFileObject> diagnostics =
            new DiagnosticCollector<JavaFileObject>();
    boolean ok = compileCode(className, contents, diagnostics);

    String expectedErrKey = "compiler.err.invalid.repeatable" +
                                    ".annotation.retention";
    if (!shouldCompile && !ok) {
        for (Diagnostic<?> d : diagnostics.getDiagnostics()) {
            if (!((d.getKind() == Diagnostic.Kind.ERROR) &&
                d.getCode().contains(expectedErrKey))) {
                error("FAIL: Incorrect error given, expected = "
                        + expectedErrKey + ", Actual = " + d.getCode()
                        + " for className = " + className, contents);
            }
        }
    }

    return (shouldCompile  == ok);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:23,代码来源:RetentionAnnoCombo.java


注:本文中的javax.tools.DiagnosticCollector类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。