本文整理汇总了Java中com.sun.tools.javac.main.JavaCompiler类的典型用法代码示例。如果您正苦于以下问题:Java JavaCompiler类的具体用法?Java JavaCompiler怎么用?Java JavaCompiler使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
JavaCompiler类属于com.sun.tools.javac.main包,在下文中一共展示了JavaCompiler类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: adjustSpans
import com.sun.tools.javac.main.JavaCompiler; //导入依赖的package包/类
private void adjustSpans(Iterable<? extends Tree> original, String code) {
if (tree2Tag == null) {
return; //nothing to copy
}
java.util.List<Tree> linearized = new LinkedList<Tree>();
if (!new Linearize().scan(original, linearized) != Boolean.TRUE) {
return; //nothing to copy
}
ClassPath empty = ClassPathSupport.createClassPath(new URL[0]);
ClasspathInfo cpInfo = ClasspathInfo.create(JavaPlatformManager.getDefault().getDefaultPlatform().getBootstrapLibraries(), empty, empty);
JavacTaskImpl javacTask = JavacParser.createJavacTask(cpInfo, null, null, null, null, null, null, null, Arrays.asList(FileObjects.memoryFileObject("", "Scratch.java", code)));
com.sun.tools.javac.util.Context ctx = javacTask.getContext();
JavaCompiler.instance(ctx).genEndPos = true;
CompilationUnitTree tree = javacTask.parse().iterator().next(); //NOI18N
SourcePositions sp = JavacTrees.instance(ctx).getSourcePositions();
ClassTree clazz = (ClassTree) tree.getTypeDecls().get(0);
new CopyTags(tree, sp).scan(clazz.getModifiers().getAnnotations(), linearized);
}
示例2: reformat
import com.sun.tools.javac.main.JavaCompiler; //导入依赖的package包/类
public static String reformat(String text, CodeStyle style, int rightMargin) {
StringBuilder sb = new StringBuilder(text);
ClassPath empty = ClassPathSupport.createClassPath(new URL[0]);
ClasspathInfo cpInfo = ClasspathInfo.create(JavaPlatformManager.getDefault().getDefaultPlatform().getBootstrapLibraries(), empty, empty);
JavacTaskImpl javacTask = JavacParser.createJavacTask(cpInfo, null, null, null, null, null, null, null, Arrays.asList(FileObjects.memoryFileObject("","Scratch.java", text)));
com.sun.tools.javac.util.Context ctx = javacTask.getContext();
JavaCompiler.instance(ctx).genEndPos = true;
CompilationUnitTree tree = javacTask.parse().iterator().next(); //NOI18N
SourcePositions sp = JavacTrees.instance(ctx).getSourcePositions();
TokenSequence<JavaTokenId> tokens = TokenHierarchy.create(text, JavaTokenId.language()).tokenSequence(JavaTokenId.language());
for (Diff diff : Pretty.reformat(text, tokens, new TreePath(tree), sp, style, rightMargin)) {
int start = diff.getStartOffset();
int end = diff.getEndOffset();
sb.delete(start, end);
String t = diff.getText();
if (t != null && t.length() > 0) {
sb.insert(start, t);
}
}
return sb.toString();
}
示例3: Round
import com.sun.tools.javac.main.JavaCompiler; //导入依赖的package包/类
/** Create a round (common code). */
private Round(Context context, int number, int priorErrors, int priorWarnings) {
this.context = context;
this.number = number;
compiler = JavaCompiler.instance(context);
log = Log.instance(context);
log.nerrors = priorErrors;
log.nwarnings += priorWarnings;
log.deferDiagnostics = true;
// the following is for the benefit of JavacProcessingEnvironment.getContext()
JavacProcessingEnvironment.this.context = context;
// the following will be populated as needed
topLevelClasses = List.nil();
packageInfoFiles = List.nil();
}
示例4: prepareCompiler
import com.sun.tools.javac.main.JavaCompiler; //导入依赖的package包/类
private void prepareCompiler() throws IOException {
if (used.getAndSet(true)) {
if (compiler == null)
throw new IllegalStateException();
} else {
initContext();
compilerMain.setOptions(Options.instance(context));
compilerMain.filenames = new LinkedHashSet<File>();
Collection<File> filenames = compilerMain.processArgs(CommandLine.parse(args), classNames);
if (!filenames.isEmpty())
throw new IllegalArgumentException("Malformed arguments " + toString(filenames, " "));
compiler = JavaCompiler.instance(context);
compiler.keepComments = true;
compiler.genEndPos = true;
// NOTE: this value will be updated after annotation processing
compiler.initProcessAnnotations(processors);
notYetEntered = new HashMap<JavaFileObject, JCCompilationUnit>();
for (JavaFileObject file: fileObjects)
notYetEntered.put(file, null);
genList = new ListBuffer<Env<AttrContext>>();
// endContext will be called when all classes have been generated
// TODO: should handle the case after each phase if errors have occurred
args = null;
classNames = null;
}
}
示例5: parseType
import com.sun.tools.javac.main.JavaCompiler; //导入依赖的package包/类
/**
* For internal use only. This method will be
* removed without warning.
*/
public Type parseType(String expr, TypeElement scope) {
if (expr == null || expr.equals(""))
throw new IllegalArgumentException();
compiler = JavaCompiler.instance(context);
JavaFileObject prev = compiler.log.useSource(null);
ParserFactory parserFactory = ParserFactory.instance(context);
Attr attr = Attr.instance(context);
try {
CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
Parser parser = parserFactory.newParser(buf, false, false, false);
JCTree tree = parser.parseType();
return attr.attribType(tree, (TypeSymbol)scope);
} finally {
compiler.log.useSource(prev);
}
}
示例6: initProcessorClassLoader
import com.sun.tools.javac.main.JavaCompiler; //导入依赖的package包/类
private void initProcessorClassLoader() {
JavaFileManager fileManager = context.get(JavaFileManager.class);
try {
// If processorpath is not explicitly set, use the classpath.
processorClassLoader = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
? fileManager.getClassLoader(ANNOTATION_PROCESSOR_PATH)
: fileManager.getClassLoader(CLASS_PATH);
if (processorClassLoader != null && processorClassLoader instanceof Closeable) {
JavaCompiler compiler = JavaCompiler.instance(context);
compiler.closeables = compiler.closeables.prepend((Closeable) processorClassLoader);
}
} catch (SecurityException e) {
processorClassLoaderException = e;
}
}
示例7: Round
import com.sun.tools.javac.main.JavaCompiler; //导入依赖的package包/类
/** Create a round (common code). */
private Round(Context context, int number, int priorErrors, int priorWarnings,
Log.DeferredDiagnosticHandler deferredDiagnosticHandler) {
this.context = context;
this.number = number;
compiler = JavaCompiler.instance(context);
log = Log.instance(context);
log.nerrors = priorErrors;
log.nwarnings = priorWarnings;
if (number == 1) {
Assert.checkNonNull(deferredDiagnosticHandler);
this.deferredDiagnosticHandler = deferredDiagnosticHandler;
} else {
this.deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log);
}
// the following is for the benefit of JavacProcessingEnvironment.getContext()
JavacProcessingEnvironment.this.context = context;
// the following will be populated as needed
topLevelClasses = List.nil();
packageInfoFiles = List.nil();
}
示例8: parseType
import com.sun.tools.javac.main.JavaCompiler; //导入依赖的package包/类
/**
* For internal use only. This method will be
* removed without warning.
*/
public Type parseType(String expr, TypeElement scope) {
if (expr == null || expr.equals(""))
throw new IllegalArgumentException();
compiler = JavaCompiler.instance(context);
JavaFileObject prev = compiler.log.useSource(null);
ParserFactory parserFactory = ParserFactory.instance(context);
Attr attr = Attr.instance(context);
try {
CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
Parser parser = parserFactory.newParser(buf, false, false, false);
JCTree tree = parser.parseType();
return attr.attribType(tree, (Symbol.TypeSymbol)scope);
} finally {
compiler.log.useSource(prev);
}
}
示例9: parseType
import com.sun.tools.javac.main.JavaCompiler; //导入依赖的package包/类
/**
* For internal use only. This method will be
* removed without warning.
* @param expr the type expression to be analyzed
* @param scope the scope in which to analyze the type expression
* @return the type
* @throws IllegalArgumentException if the type expression of null or empty
*/
public Type parseType(String expr, TypeElement scope) {
if (expr == null || expr.equals(""))
throw new IllegalArgumentException();
compiler = JavaCompiler.instance(context);
JavaFileObject prev = compiler.log.useSource(null);
ParserFactory parserFactory = ParserFactory.instance(context);
Attr attr = Attr.instance(context);
try {
CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
Parser parser = parserFactory.newParser(buf, false, false, false);
JCTree tree = parser.parseType();
return attr.attribType(tree, (Symbol.TypeSymbol)scope);
} finally {
compiler.log.useSource(prev);
}
}
示例10: GraphDependencies
import com.sun.tools.javac.main.JavaCompiler; //导入依赖的package包/类
/**
* Build a Dependencies instance.
*/
GraphDependencies(Context context) {
super(context);
//fetch filename
Options options = Options.instance(context);
String[] modes = options.get("debug.completionDeps").split(",");
for (String mode : modes) {
if (mode.startsWith("file=")) {
dependenciesFile = mode.substring(5);
}
}
//parse modes
dependenciesModes = DependenciesMode.getDependenciesModes(modes);
//add to closeables
JavaCompiler compiler = JavaCompiler.instance(context);
compiler.closeables = compiler.closeables.prepend(this);
}
示例11: PubApiExtractor
import com.sun.tools.javac.main.JavaCompiler; //导入依赖的package包/类
/**
* Setup a compilation context, used for reading public apis of classes on the classpath
* as well as annotation processors.
*/
public PubApiExtractor(Options options) {
JavacTool compiler = com.sun.tools.javac.api.JavacTool.create();
fileManager = new SmartFileManager(compiler.getStandardFileManager(null, null, null));
context = new com.sun.tools.javac.util.Context();
String[] args = options.prepJavacArgs();
task = compiler.getTask(new PrintWriter(System.err),
fileManager,
null,
Arrays.asList(args),
null,
null,
context);
// Trigger a creation of the JavaCompiler, necessary to get a sourceCompleter for ClassFinder.
// The sourceCompleter is used for build situations where a classpath class references other classes
// that happens to be on the sourcepath.
JavaCompiler.instance(context);
// context.put(JavaFileManager.class, fileManager);
}
示例12: test
import com.sun.tools.javac.main.JavaCompiler; //导入依赖的package包/类
static void test(JavacFileManager fm, JavaFileObject f, List<String> addExports, String... args) throws Throwable {
List<String> allArgs = new ArrayList<>();
allArgs.addAll(addExports);
allArgs.addAll(Arrays.asList(args));
Context context = new Context();
JavacTool tool = JavacTool.create();
JavacTaskImpl task = (JavacTaskImpl) tool.getTask(null, fm, null, allArgs, null, List.of(f), context);
task.call();
JavaCompiler c = JavaCompiler.instance(context);
if (c.errorCount() != 0)
throw new AssertionError("compilation failed");
long msec = c.elapsed_msec;
if (msec < 0 || msec > 5 * 60 * 1000) // allow test 5 mins to execute, should be more than enough!
throw new AssertionError("elapsed time is suspect: " + msec);
}
示例13: main
import com.sun.tools.javac.main.JavaCompiler; //导入依赖的package包/类
public static void main(String... args) {
JavaCompiler compiler = JavaCompiler.instance(new Context());
compiler.keepComments = true;
String testSrc = System.getProperty("test.src");
JavacFileManager fm = new JavacFileManager(new Context(), false, null);
JavaFileObject f = fm.getJavaFileObject(testSrc + File.separatorChar + "T4910483.java");
JCTree.JCCompilationUnit cu = compiler.parse(f);
JCTree classDef = cu.getTypeDecls().head;
String commentText = cu.docComments.getCommentText(classDef);
String expected = "Test comment abc*\\\\def"; // 4 '\' escapes to 2 in a string literal
if (!expected.equals(commentText)) {
throw new AssertionError("Incorrect comment text: [" + commentText + "], expected [" + expected + "]");
}
}
示例14: testNoAnnotationProcessing
import com.sun.tools.javac.main.JavaCompiler; //导入依赖的package包/类
static void testNoAnnotationProcessing(JavacFileManager fm, List<JavaFileObject> files) throws Throwable {
Context context = new Context();
String[] args = { "-d", "." };
JavacTool tool = JavacTool.create();
JavacTask task = tool.getTask(null, fm, null, List.from(args), null, files, context);
// no need in this simple case to call task.prepareCompiler(false)
JavaCompiler compiler = JavaCompiler.instance(context);
compiler.compile(files);
try {
compiler.compile(files);
throw new Error("Error: AssertionError not thrown after second call of compile");
} catch (AssertionError e) {
System.err.println("Exception from compiler (expected): " + e);
}
}
示例15: testAnnotationProcessing
import com.sun.tools.javac.main.JavaCompiler; //导入依赖的package包/类
static void testAnnotationProcessing(JavacFileManager fm, List<JavaFileObject> files) throws Throwable {
Context context = new Context();
String[] args = {
"-XprintRounds",
"-processorpath", testClasses,
"-processor", self,
"-d", "."
};
JavacTool tool = JavacTool.create();
JavacTask task = tool.getTask(null, fm, null, List.from(args), null, files, context);
// no need in this simple case to call task.prepareCompiler(false)
JavaCompiler compiler = JavaCompiler.instance(context);
compiler.compile(files);
try {
compiler.compile(files);
throw new Error("Error: AssertionError not thrown after second call of compile");
} catch (AssertionError e) {
System.err.println("Exception from compiler (expected): " + e);
}
}