Example usage for javax.tools Diagnostic getLineNumber

List of usage examples for javax.tools Diagnostic getLineNumber

Introduction

In this page you can find the example usage for javax.tools Diagnostic getLineNumber.

Prototype

long getLineNumber();

Source Link

Document

Returns the line number of the character offset returned by #getPosition() .

Usage

From source file:zhwb.study.compiler.CachedCompiler.java

public Map<String, byte[]> compileFromJava(String className, String javaCode) {
    Iterable<? extends JavaFileObject> compilationUnits;
    if (sourceDir != null) {
        String filename = className.replaceAll("\\.", '\\' + File.separator) + ".java";
        File file = new File(sourceDir, filename);
        writeText(file, javaCode);//  w ww  . j  av a  2 s .c o  m
        compilationUnits = CompilerUtils.s_standardJavaFileManager.getJavaFileObjects(file);

    } else {
        javaFileObjects.add(new JavaSourceFromString(className, javaCode));
        compilationUnits = javaFileObjects;
    }
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

    // reuse the same file manager to allow caching of jar files
    Boolean status = CompilerUtils.s_compiler
            .getTask(null, CompilerUtils.s_fileManager, diagnostics, null, null, compilationUnits).call();
    if (!status) {//If compilation error occurs
        /*Iterate through each compilation problem and print it*/
        StringBuilder sb = new StringBuilder();
        sb.append(StringUtils.LF);
        for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
            sb.append(String.format("Error on line %d in %s", diagnostic.getLineNumber(), diagnostic))
                    .append(StringUtils.LF);
        }
        throw new IllegalStateException(String.format("compile error, %s", sb.toString()));
    }
    return CompilerUtils.s_fileManager.getAllBuffers();
}