javax.tools.SimpleJavaFileObject Java Examples

The following examples show how to use javax.tools.SimpleJavaFileObject. 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
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException {
    try {
        return new SimpleJavaFileObject(new URI("mem://" + className.replace('.', '/') + kind.extension), kind) {
            @Override public OutputStream openOutputStream() throws IOException {
                return new ByteArrayOutputStream() {
                    @Override public void close() throws IOException {
                        super.close();
                        name2Content.put(className, toByteArray());
                    }
                };
            }
        };
    } catch (URISyntaxException ex) {
        throw new AssertionError(ex);
    }
}
 
Example #2
Source Project: TencentKona-8   Author: Tencent   File: T6733837.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void exec() {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "\tclass ErroneousWithTab";
        }
    };
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    task = tool.getTask(sw, fm, null, null, null, files);
    try {
        ((JavacTask)task).analyze();
    }
    catch (Throwable t) {
        throw new Error("Compiler threw an exception");
    }
    System.err.println(sw.toString());
    if (!sw.toString().contains("/Test.java"))
        throw new Error("Bad source name in diagnostic");
}
 
Example #3
Source Project: TencentKona-8   Author: Tencent   File: T6852595.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "class BadName { Object o = j; }";
        }
    };
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, files);
    Iterable<? extends CompilationUnitTree> compUnits = ct.parse();
    CompilationUnitTree cu = compUnits.iterator().next();
    ClassTree cdef = (ClassTree)cu.getTypeDecls().get(0);
    JCVariableDecl vdef = (JCVariableDecl)cdef.getMembers().get(0);
    TreePath path = TreePath.getPath(cu, vdef.init);
    Trees.instance(ct).getScope(path);
}
 
Example #4
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: T6852595.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "class BadName { Object o = j; }";
        }
    };
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, files);
    Iterable<? extends CompilationUnitTree> compUnits = ct.parse();
    CompilationUnitTree cu = compUnits.iterator().next();
    ClassTree cdef = (ClassTree)cu.getTypeDecls().get(0);
    JCVariableDecl vdef = (JCVariableDecl)cdef.getMembers().get(0);
    TreePath path = TreePath.getPath(cu, vdef.init);
    Trees.instance(ct).getScope(path);
}
 
Example #5
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: JavaLexerTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
void run() throws Exception {
    Context ctx = new Context();
    Log log = Log.instance(ctx);
    String input = "0bL 0b20L 0xL ";
    log.useSource(new SimpleJavaFileObject(new URI("mem://Test.java"), JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return input;
        }
    });
    char[] inputArr = input.toCharArray();
    JavaTokenizer tokenizer = new JavaTokenizer(ScannerFactory.instance(ctx), inputArr, inputArr.length) {
    };

    assertKind(input, tokenizer, TokenKind.LONGLITERAL, "0bL");
    assertKind(input, tokenizer, TokenKind.LONGLITERAL, "0b20L");
    assertKind(input, tokenizer, TokenKind.LONGLITERAL, "0xL");
}
 
Example #6
Source Project: jdk8u60   Author: chenghanpeng   File: T6733837.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void exec() {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "\tclass ErroneousWithTab";
        }
    };
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    task = tool.getTask(sw, fm, null, null, null, files);
    try {
        ((JavacTask)task).analyze();
    }
    catch (Throwable t) {
        throw new Error("Compiler threw an exception");
    }
    System.err.println(sw.toString());
    if (!sw.toString().contains("/Test.java"))
        throw new Error("Bad source name in diagnostic");
}
 
Example #7
Source Project: jdk8u60   Author: chenghanpeng   File: T6852595.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "class BadName { Object o = j; }";
        }
    };
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, files);
    Iterable<? extends CompilationUnitTree> compUnits = ct.parse();
    CompilationUnitTree cu = compUnits.iterator().next();
    ClassTree cdef = (ClassTree)cu.getTypeDecls().get(0);
    JCVariableDecl vdef = (JCVariableDecl)cdef.getMembers().get(0);
    TreePath path = TreePath.getPath(cu, vdef.init);
    Trees.instance(ct).getScope(path);
}
 
Example #8
Source Project: java-n-IDE-for-Android   Author: shenghuntianlang   File: JavaParser.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
public JCTree.JCCompilationUnit parse(final String src) {
    if (!canParse) return null;
    long time = System.currentTimeMillis();

    SimpleJavaFileObject source = new SimpleJavaFileObject(URI.create("source"), JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return src;
        }
    };
    Log.instance(context).useSource(source);
    Parser parser = parserFactory.newParser(src,
        /*keepDocComments=*/ true,
        /*keepEndPos=*/ true,
        /*keepLineMap=*/ true);
    JCTree.JCCompilationUnit unit;
    unit = parser.parseCompilationUnit();
    unit.sourcefile = source;
    android.util.Log.d(TAG, "parse: time " + (System.currentTimeMillis() - time) + " ms");
    return unit;
}
 
Example #9
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: TestNonSerializableLambdaNameStability.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException {
    try {
        return new SimpleJavaFileObject(new URI("mem://" + className.replace('.', '/') + kind.extension), kind) {
            @Override public OutputStream openOutputStream() throws IOException {
                return new ByteArrayOutputStream() {
                    @Override public void close() throws IOException {
                        super.close();
                        name2Content.put(className, toByteArray());
                    }
                };
            }
        };
    } catch (URISyntaxException ex) {
        throw new AssertionError(ex);
    }
}
 
Example #10
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: T6733837.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void exec() {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "\tclass ErroneousWithTab";
        }
    };
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    task = tool.getTask(sw, fm, null, null, null, files);
    try {
        ((JavacTask)task).analyze();
    }
    catch (Throwable t) {
        throw new Error("Compiler threw an exception");
    }
    System.err.println(sw.toString());
    if (!sw.toString().contains("/Test.java"))
        throw new Error("Bad source name in diagnostic");
}
 
Example #11
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: T6852595.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "class BadName { Object o = j; }";
        }
    };
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, files);
    Iterable<? extends CompilationUnitTree> compUnits = ct.parse();
    CompilationUnitTree cu = compUnits.iterator().next();
    ClassTree cdef = (ClassTree)cu.getTypeDecls().get(0);
    JCVariableDecl vdef = (JCVariableDecl)cdef.getMembers().get(0);
    TreePath path = TreePath.getPath(cu, vdef.init);
    Trees.instance(ct).getScope(path);
}
 
Example #12
Source Project: netbeans   Author: apache   File: BootClassPathUtil.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, javax.tools.FileObject sibling) throws IOException {
    if (location == StandardLocation.CLASS_OUTPUT) {
        String relPath = className.replace('.', '/') + ".class";
        try {
            return new SimpleJavaFileObject(new URI("mem://" + relPath), kind) {
                @Override
                public OutputStream openOutputStream() throws IOException {
                    return new ByteArrayOutputStream() {
                        @Override
                        public void close() throws IOException {
                            super.close();
                            FileObject target = FileUtil.createData(sink, relPath);
                            try (OutputStream out = target.getOutputStream()) {
                                out.write(toByteArray());
                            }
                        }
                    };
                }
            };
        } catch (URISyntaxException ex) {
            throw new IOException(ex);
        }
    }
    return super.getJavaFileForOutput(location, className, kind, sibling);
}
 
Example #13
Source Project: netbeans   Author: apache   File: BootClassPathUtil.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, javax.tools.FileObject sibling) throws IOException {
    if (location == StandardLocation.CLASS_OUTPUT) {
        String relPath = className.replace('.', '/') + ".class";
        try {
            return new SimpleJavaFileObject(new URI("mem://" + relPath), kind) {
                @Override
                public OutputStream openOutputStream() throws IOException {
                    return new ByteArrayOutputStream() {
                        @Override
                        public void close() throws IOException {
                            super.close();
                            FileObject target = FileUtil.createData(sink, relPath);
                            try (OutputStream out = target.getOutputStream()) {
                                out.write(toByteArray());
                            }
                        }
                    };
                }
            };
        } catch (URISyntaxException ex) {
            throw new IOException(ex);
        }
    }
    return super.getJavaFileForOutput(location, className, kind, sibling);
}
 
Example #14
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException {
    try {
        return new SimpleJavaFileObject(new URI("mem://" + className.replace('.', '/') + kind.extension), kind) {
            @Override public OutputStream openOutputStream() throws IOException {
                return new ByteArrayOutputStream() {
                    @Override public void close() throws IOException {
                        super.close();
                        name2Content.put(className, toByteArray());
                    }
                };
            }
        };
    } catch (URISyntaxException ex) {
        throw new AssertionError(ex);
    }
}
 
Example #15
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: T6733837.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void exec() {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "\tclass ErroneousWithTab";
        }
    };
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    task = tool.getTask(sw, fm, null, null, null, files);
    try {
        ((JavacTask)task).analyze();
    }
    catch (Throwable t) {
        throw new Error("Compiler threw an exception");
    }
    System.err.println(sw.toString());
    if (!sw.toString().contains("/Test.java"))
        throw new Error("Bad source name in diagnostic");
}
 
Example #16
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: T6852595.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "class BadName { Object o = j; }";
        }
    };
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, files);
    Iterable<? extends CompilationUnitTree> compUnits = ct.parse();
    CompilationUnitTree cu = compUnits.iterator().next();
    ClassTree cdef = (ClassTree)cu.getTypeDecls().get(0);
    JCVariableDecl vdef = (JCVariableDecl)cdef.getMembers().get(0);
    TreePath path = TreePath.getPath(cu, vdef.init);
    Trees.instance(ct).getScope(path);
}
 
Example #17
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: T6733837.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void exec() {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "\tclass ErroneousWithTab";
        }
    };
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    task = tool.getTask(sw, fm, null, null, null, files);
    try {
        ((JavacTask)task).analyze();
    }
    catch (Throwable t) {
        throw new Error("Compiler threw an exception");
    }
    System.err.println(sw.toString());
    if (!sw.toString().contains("/Test.java"))
        throw new Error("Bad source name in diagnostic");
}
 
Example #18
Source Project: TencentKona-8   Author: Tencent   File: RunTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
JavaFileObject createFile(String name, final String body) {
    return new SimpleJavaFileObject(URI.create(name), JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return body;
        }
    };
}
 
Example #19
Source Project: TencentKona-8   Author: Tencent   File: APITest.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected JavaFileObject createSimpleJavaFileObject(final String binaryName, final String content) {
    return new SimpleJavaFileObject(
            URI.create("myfo:///" + binaryName + ".java"), JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncoding) {
            return content;
        }
    };
}
 
Example #20
Source Project: TencentKona-8   Author: Tencent   File: CompletionFailure.java    License: GNU General Public License v2.0 5 votes vote down vote up
SimpleJavaFileObject asJFO(java.io.File dir) {
    return new SimpleJavaFileObject(new File(dir, filename).toURI(), JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return contents;
        }
    };
}
 
Example #21
Source Project: TencentKona-8   Author: Tencent   File: Abort.java    License: GNU General Public License v2.0 5 votes vote down vote up
SimpleJavaFileObject asJFO(java.io.File dir) {
    return new SimpleJavaFileObject(new java.io.File(dir, filename).toURI(), JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return contents;
        }
    };
}
 
Example #22
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: TestCircularClassfile.java    License: GNU General Public License v2.0 5 votes vote down vote up
SimpleJavaFileObject getSource() {
    return new SimpleJavaFileObject(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return "class Test { public static void main(String[] args) { #M } }"
                    .replace("#M", mainMethod);
        }
    };
}
 
Example #23
Source Project: TencentKona-8   Author: Tencent   File: ScopeTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static void verifyLambdaScopeCorrect(final String packageClause) throws Exception {
    JavacTool tool = JavacTool.create();
    JavaFileObject source = new SimpleJavaFileObject(URI.create("mem://Test.java"), Kind.SOURCE) {
        @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return packageClause + SOURCE_CODE;
        }
        @Override public boolean isNameCompatible(String simpleName, Kind kind) {
            return true;
        }
    };
    Iterable<? extends JavaFileObject> fos = Collections.singletonList(source);
    JavacTask task = tool.getTask(null, null, null, new ArrayList<String>(), null, fos);
    final Types types = JavacTypes.instance(((JavacTaskImpl) task).getContext());
    final Trees trees = Trees.instance(task);
    CompilationUnitTree cu = task.parse().iterator().next();

    task.analyze();

    new TreePathScanner<Void, Void>() {
        @Override public Void visitMemberSelect(MemberSelectTree node, Void p) {
            if (node.getIdentifier().contentEquals("correct")) {
                TypeMirror xType = trees.getTypeMirror(new TreePath(getCurrentPath(), node.getExpression()));
                Scope scope = trees.getScope(getCurrentPath());
                for (Element l : scope.getLocalElements()) {
                    if (!l.getSimpleName().contentEquals("x")) continue;
                    if (!types.isSameType(xType, l.asType())) {
                        throw new IllegalStateException("Incorrect variable type in scope: " + l.asType() + "; should be: " + xType);
                    }
                }
            }
            return super.visitMemberSelect(node, p);
        }
    }.scan(cu, null);
}
 
Example #24
Source Project: TencentKona-8   Author: Tencent   File: EndPositions.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    class MyFileObject extends SimpleJavaFileObject {
        MyFileObject() {
            super(URI.create("myfo:///Test.java"), SOURCE);
        }
        @Override
        public String getCharContent(boolean ignoreEncodingErrors) {
            //      0         1         2         3
            //      012345678901234567890123456789012345
            return "class Test { String s = 1234; }";
        }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits =
            Collections.<JavaFileObject>singletonList(new MyFileObject());
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    List<String> options = Arrays.asList("-processor", EndPositions.class.getCanonicalName());
    JavacTask task = (JavacTask)javac.getTask(null, null, diagnostics, options, null, compilationUnits);
    boolean valid = task.call();
    if (valid)
        throw new AssertionError("Expected one error, but found none.");

    List<Diagnostic<? extends JavaFileObject>> errors = diagnostics.getDiagnostics();
    if (errors.size() != 1)
        throw new AssertionError("Expected one error only, but found " + errors.size() + "; errors: " + errors);

    Diagnostic<?> error = errors.get(0);
    if (error.getStartPosition() >= error.getEndPosition())
        throw new AssertionError("Expected start to be less than end position: start [" +
                error.getStartPosition() + "], end [" + error.getEndPosition() +"]" +
                "; diagnostics code: " + error.getCode());

    System.out.println("All is good!");
}
 
Example #25
Source Project: TencentKona-8   Author: Tencent   File: T6608214.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create(""),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "class Test<S> { <T extends S & Runnable> void test(){}}";
        }
    };
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    String bootPath = System.getProperty("sun.boot.class.path");
    List<String> opts = Arrays.asList("-bootclasspath",  bootPath, "-Xjcov");
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask)tool.getTask(null, null, null,opts,null,files);
    ct.analyze();
}
 
Example #26
Source Project: TencentKona-8   Author: Tencent   File: T6402077.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    class MyFileObject extends SimpleJavaFileObject {
        MyFileObject() {
            super(URI.create("myfo:///Test.java"), SOURCE);
        }
        @Override
        public String getCharContent(boolean ignoreEncodingErrors) {
            //      0         1         2
            //      0123456789012345678901234
            return "class Test { Test() { } }";
        }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits =
            Collections.<JavaFileObject>singletonList(new MyFileObject());
    JavacTask task = (JavacTask)javac.getTask(null, null, null, null, null,
                                              compilationUnits);
    Trees trees = Trees.instance(task);
    CompilationUnitTree toplevel = task.parse().iterator().next();
    Tree tree = ((ClassTree)toplevel.getTypeDecls().get(0)).getMembers().get(0);
    long pos = trees.getSourcePositions().getStartPosition(toplevel, tree);
    if (pos != 13)
        throw new AssertionError(String.format("Start pos for %s is incorrect (%s)!",
                                               tree, pos));
    pos = trees.getSourcePositions().getEndPosition(toplevel, tree);
    if (pos != 23)
        throw new AssertionError(String.format("End pos for %s is incorrect (%s)!",
                                               tree, pos));
}
 
Example #27
Source Project: TencentKona-8   Author: Tencent   File: T6404194.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    class MyFileObject extends SimpleJavaFileObject {
        MyFileObject() {
            super(URI.create("myfo:///Test.java"), SOURCE);
        }
        @Override
        public String getCharContent(boolean ignoreEncodingErrors) {
            //      0         1          2          3
            //      01234567890123456 7890 123456789012345
            return "@SuppressWarning(\"foo\") @Deprecated class Test { Test() { } }";
        }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits =
            Collections.<JavaFileObject>singletonList(new MyFileObject());
    JavacTask task = (JavacTask)javac.getTask(null, null, null, null, null, compilationUnits);
    Trees trees = Trees.instance(task);
    CompilationUnitTree toplevel = task.parse().iterator().next();
    ClassTree classTree = (ClassTree)toplevel.getTypeDecls().get(0);
    List<? extends Tree> annotations = classTree.getModifiers().getAnnotations();
    Tree tree1 = annotations.get(0);
    Tree tree2 = annotations.get(1);
    long pos = trees.getSourcePositions().getStartPosition(toplevel, tree1);
    if (pos != 0)
        throw new AssertionError(String.format("Start pos for %s is incorrect (%s)!",
                                               tree1, pos));
    pos = trees.getSourcePositions().getEndPosition(toplevel, tree1);
    if (pos != 23)
        throw new AssertionError(String.format("End pos for %s is incorrect (%s)!",
                                               tree1, pos));
    pos = trees.getSourcePositions().getStartPosition(toplevel, tree2);
    if (pos != 24)
        throw new AssertionError(String.format("Start pos for %s is incorrect (%s)!",
                                               tree2, pos));
    pos = trees.getSourcePositions().getEndPosition(toplevel, tree2);
    if (pos != 35)
        throw new AssertionError(String.format("End pos for %s is incorrect (%s)!",
                                               tree2, pos));
}
 
Example #28
Source Project: jdk8u60   Author: chenghanpeng   File: RunTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
JavaFileObject createFile(String name, final String body) {
    return new SimpleJavaFileObject(URI.create(name), JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return body;
        }
    };
}
 
Example #29
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: APITest.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected JavaFileObject createSimpleJavaFileObject(final String binaryName, final String content) {
    return new SimpleJavaFileObject(
            URI.create("myfo:///" + binaryName + ".java"), JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncoding) {
            return content;
        }
    };
}
 
Example #30
Source Project: jdk8u60   Author: chenghanpeng   File: Abort.java    License: GNU General Public License v2.0 5 votes vote down vote up
SimpleJavaFileObject asJFO(java.io.File dir) {
    return new SimpleJavaFileObject(new java.io.File(dir, filename).toURI(), JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return contents;
        }
    };
}