當前位置: 首頁>>代碼示例>>Java>>正文


Java DiagnosticCollector.getDiagnostics方法代碼示例

本文整理匯總了Java中javax.tools.DiagnosticCollector.getDiagnostics方法的典型用法代碼示例。如果您正苦於以下問題:Java DiagnosticCollector.getDiagnostics方法的具體用法?Java DiagnosticCollector.getDiagnostics怎麽用?Java DiagnosticCollector.getDiagnostics使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在javax.tools.DiagnosticCollector的用法示例。


在下文中一共展示了DiagnosticCollector.getDiagnostics方法的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: compileFile

import javax.tools.DiagnosticCollector; //導入方法依賴的package包/類
@SafeVarargs
private final void compileFile( JavacTool javacTool, JavaFileManager fileManager, String file, Pair<IssueMsg, Integer>... msgs ) throws IOException, URISyntaxException
{
  DiagnosticCollector<JavaFileObject> dc = new DiagnosticCollector<>();
  String content = StreamUtil.getContent( StreamUtil.getInputStreamReader( getClass().getResourceAsStream( file ) ) );
  SourceFile srcFile = new SourceFile( file, content );
  StringWriter errors = new StringWriter();
  JavacTaskImpl javacTask = (JavacTaskImpl)javacTool.getTask( errors, fileManager, dc, Collections.singletonList( "-Xplugin:Manifold" ), null, Collections.singletonList( srcFile ) );
  javacTask.call();
  outer:
  for( Pair<IssueMsg, Integer> msg : msgs )
  {
    for( Diagnostic<? extends JavaFileObject> d : dc.getDiagnostics() )
    {
      if( d.getLineNumber() == msg.getSecond() )
      {
        if( msg.getFirst().isMessageSimilar( d.getMessage( Locale.getDefault() ) ) )
        {
          continue outer;
        }
      }
    }
    fail( "Did not find issue: " + msg.getFirst().get() + " at line: " + msg.getSecond() );
  }
}
 
開發者ID:manifold-systems,項目名稱:manifold,代碼行數:26,代碼來源:CompilationTest.java

示例3: 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

示例4: 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

示例5: 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

示例6: 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

示例7: 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:campolake,項目名稱:openjdk9,代碼行數:26,代碼來源:JavapTaskCtorFailWithNPE.java

示例8: 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, null, 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:ojdkbuild,項目名稱:lookaside_java-1.8.0-openjdk,代碼行數:23,代碼來源:JavacParserTest.java

示例9: 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:ojdkbuild,項目名稱:lookaside_java-1.8.0-openjdk,代碼行數:18,代碼來源:T7190862.java

示例10: compile

import javax.tools.DiagnosticCollector; //導入方法依賴的package包/類
/** Convenient JavaCompiler facade returning a ClassLoader with all compiled units. */
static ClassLoader compile(
    ClassLoader parent,
    List<String> options,
    List<Processor> processors,
    List<JavaFileObject> units) {
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  Objects.requireNonNull(compiler, "no system java compiler available - JDK is required!");
  DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
  StandardJavaFileManager sjfm =
      compiler.getStandardFileManager(diagnostics, Locale.getDefault(), StandardCharsets.UTF_8);
  Manager manager = new Manager(sjfm, parent);
  CompilationTask task = compiler.getTask(null, manager, diagnostics, options, null, units);
  if (!processors.isEmpty()) {
    task.setProcessors(processors);
  }
  boolean success = task.call();
  if (!success) {
    throw new RuntimeException("compilation failed! " + diagnostics.getDiagnostics());
  }
  return manager.getClassLoader(StandardLocation.CLASS_PATH);
}
 
開發者ID:sormuras,項目名稱:listing,代碼行數:23,代碼來源:Compilation.java

示例11: compile

import javax.tools.DiagnosticCollector; //導入方法依賴的package包/類
static void compile(JavaSource src) throws IOException {
    ByteArrayOutputStream ba = new ByteArrayOutputStream();
    PrintWriter writer = new PrintWriter(ba);
    File tempDir = new File(".");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector dc = new DiagnosticCollector();
    try (JavaFileManager javaFileManager = getJavaFileManager(compiler, dc)) {
        List<String> options = new ArrayList<>();
        options.add("-cp");
        options.add(tempDir.getPath());
        options.add("-d");
        options.add(tempDir.getPath());
        options.add("--should-stop:at=GENERATE");

        List<JavaFileObject> sources = new ArrayList<>();
        sources.add(src);
        JavaCompiler.CompilationTask task =
                compiler.getTask(writer, javaFileManager,
                dc, options, null,
                sources);
        task.call();
        for (Diagnostic diagnostic : (List<Diagnostic>) dc.getDiagnostics()) {
            long actualStart = diagnostic.getStartPosition();
            long actualEnd = diagnostic.getEndPosition();
            System.out.println("Source: " + src.source);
            System.out.println("Diagnostic: " + diagnostic);
            System.out.print("Start position: Expected: " + src.startPos);
            System.out.println(", Actual: " + actualStart);
            System.out.print("End position: Expected: " + src.endPos);
            System.out.println(", Actual: " + actualEnd);
            if (src.startPos != actualStart || src.endPos != actualEnd) {
                throw new RuntimeException("error: trees don't match");
            }
        }
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:37,代碼來源:TreeEndPosTest.java

示例12: makeMessage

import javax.tools.DiagnosticCollector; //導入方法依賴的package包/類
private static String makeMessage( String fqn, DiagnosticCollector<JavaFileObject> errorHandler )
{
  StringBuilder sb = new StringBuilder( "Error compiling Java class: " + fqn + "\n" );
  if( errorHandler == null || errorHandler.getDiagnostics() == null )
  {
    return sb.append( "No error messages available" ).toString();
  }
  sb.append( "\n" );
  for( Diagnostic d : errorHandler.getDiagnostics() )
  {
    sb.append( d.toString() ).append( "\n" );
  }
  return sb.toString();
}
 
開發者ID:manifold-systems,項目名稱:manifold,代碼行數:15,代碼來源:JavaCompileIssuesException.java

示例13: createCompilationErrorException

import javax.tools.DiagnosticCollector; //導入方法依賴的package包/類
@Override
protected IllegalStateException createCompilationErrorException(JavaFileObjectRegistry registry, DiagnosticCollector<JavaFileObject> diagnostics) {
  final ArrayList<CompilationException.CompilationError> compilationErrors = new ArrayList<>();
  for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
    compilationErrors.add(new CompilationException.CompilationError(((int) diagnostic.getLineNumber()), diagnostic.getMessage(null), getErrorDetails(diagnostic)));
  }
  return new CompilationException(format("%d compilation error(s)\n", compilationErrors.size()), compilationErrors);
}
 
開發者ID:twosigma,項目名稱:beaker-notebook-archive,代碼行數:9,代碼來源:JavaSourceCompiler.java

示例14: showDiagnostics

import javax.tools.DiagnosticCollector; //導入方法依賴的package包/類
private void showDiagnostics(DiagnosticCollector<JavaFileObject> diagnostics) {
	String message;
	for (Diagnostic<?> diagnostic : diagnostics.getDiagnostics()) {
		if (StringUtils.equals(diagnostic.getKind().name(), Diagnostic.Kind.ERROR.name())) {
			message = diagnostic.getMessage(null);
			new CustomMessageBox(SWT.ERROR, message, Messages.INVALID_EXPRESSION_TITLE).open();
		} else {
			new CustomMessageBox(SWT.ICON_INFORMATION, Messages.VALID_EXPRESSION_TITLE, Messages.VALID_EXPRESSION_TITLE).open();
		}
		break;
	}
}
 
開發者ID:capitalone,項目名稱:Hydrograph,代碼行數:13,代碼來源:ValidateExpressionToolButton.java

示例15: testDiagListener

import javax.tools.DiagnosticCollector; //導入方法依賴的package包/類
/**
 * Verify that a diagnostic listener can be specified.
 * Note that messages from the tool and doclet are imperfectly modeled
 * because the DocErrorReporter API works in terms of localized strings
 * and file:line positions. Therefore, messages reported via DocErrorReporter
 * and simply wrapped and passed through.
 */
@Test
public void testDiagListener() throws Exception {
    JavaFileObject srcFile = createSimpleJavaFileObject("pkg/C", "package pkg; public error { }");
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    try (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);
        DiagnosticCollector<JavaFileObject> dc = new DiagnosticCollector<JavaFileObject>();
        DocumentationTask t = tool.getTask(null, fm, dc, null, null, files);
        if (t.call()) {
            throw new Exception("task succeeded unexpectedly");
        } else {
            List<String> diagCodes = new ArrayList<String>();
            for (Diagnostic d: dc.getDiagnostics()) {
                System.err.println(d);
                diagCodes.add(d.getCode());
            }
            List<String> expect = Arrays.asList(
                    "javadoc.note.msg",         // Loading source file
                    "compiler.err.expected3",   // class, interface, or enum expected
                    "javadoc.note.msg");        // 1 error
            if (!diagCodes.equals(expect))
                throw new Exception("unexpected diagnostics occurred");
            System.err.println("diagnostics received as expected");
        }
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:36,代碼來源:GetTask_DiagListenerTest.java


注:本文中的javax.tools.DiagnosticCollector.getDiagnostics方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。