本文整理汇总了Java中javax.tools.JavaCompiler.getTask方法的典型用法代码示例。如果您正苦于以下问题:Java JavaCompiler.getTask方法的具体用法?Java JavaCompiler.getTask怎么用?Java JavaCompiler.getTask使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.tools.JavaCompiler
的用法示例。
在下文中一共展示了JavaCompiler.getTask方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: run
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
public void run() throws IOException {
File srcDir = new File(System.getProperty("test.src"));
File thisFile = new File(srcDir, getClass().getName() + ".java");
JavaCompiler c = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager fm = c.getStandardFileManager(null, null, null)) {
List<String> opts = Arrays.asList("-proc:only", "-doe");
Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(thisFile);
JavacTask t = (JavacTask) c.getTask(null, fm, null, opts, null, files);
t.setProcessors(Collections.singleton(this));
boolean ok = t.call();
if (!ok)
throw new Error("compilation failed");
}
}
示例2: run
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
public void run(JavaCompiler comp) {
JavaSource source = new JavaSource();
JavacTaskImpl ct = (JavacTaskImpl)comp.getTask(null, null, dc,
Arrays.asList("-g"), null, Arrays.asList(source));
Context context = ct.getContext();
Symtab syms = Symtab.instance(context);
Names names = Names.instance(context);
Types types = Types.instance(context);
ct.addTaskListener(new Indifier(syms, names, types));
try {
ct.generate();
} catch (Throwable t) {
t.printStackTrace();
throw new AssertionError(
String.format("Error thrown when compiling following code\n%s",
source.source));
}
if (dc.diagFound) {
throw new AssertionError(
String.format("Diags found when compiling following code\n%s\n\n%s",
source.source, dc.printDiags()));
}
verifyBytecode();
}
示例3: main
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
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);
}
示例4: main
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
File src = new File("C.java");
Writer w = new FileWriter(src);
try {
w.write("import static p.Generated.m;\nclass C { {m(); } }\n");
w.flush();
} finally {
w.close();
}
JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager fm = jc.getStandardFileManager(null, null, null)) {
JavaCompiler.CompilationTask task = jc.getTask(null, fm, null, null, null,
fm.getJavaFileObjects(src));
task.setProcessors(Collections.singleton(new Proc()));
if (!task.call()) {
throw new Error("Test failed");
}
}
}
示例5: compileDependencyClass
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
@BeforeClass
public static void compileDependencyClass() throws IOException, ClassNotFoundException {
JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
Assume.assumeNotNull(javaCompiler);
classes = temporaryFolder.newFolder("classes");;
StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, Locale.ROOT, UTF_8);
fileManager.setLocation(StandardLocation.CLASS_OUTPUT, ImmutableList.of(classes));
SimpleJavaFileObject compilationUnit = new SimpleJavaFileObject(URI.create("FooTest.java"), Kind.SOURCE) {
String fooTestSource = Resources.toString(Resources.getResource("com/dremio/exec/compile/FooTest.java"), UTF_8);
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
return fooTestSource;
}
};
CompilationTask task = javaCompiler.getTask(null, fileManager, null, Collections.<String>emptyList(), null, ImmutableList.of(compilationUnit));
assertTrue(task.call());
}
示例6: compile
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
private File compile(List<File> classpaths, List<JavaFileObject> files, boolean generate) throws IOException {
JavaCompiler systemJavaCompiler = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager fm = systemJavaCompiler.getStandardFileManager(null, null, null)) {
if (classpaths.size() > 0)
fm.setLocation(StandardLocation.CLASS_PATH, classpaths);
JavacTask ct = (JavacTask) systemJavaCompiler.getTask(null, fm, diags, compileOptions, null, files);
if (generate) {
File destDir = new File(root, Integer.toString(counter.incrementAndGet()));
// @@@ Assert that this directory didn't exist, or start counter at max+1
destDir.mkdirs();
fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir));
ct.generate();
return destDir;
}
else {
ct.analyze();
return nullDir;
}
}
}
示例7: run
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception {
checkCount++;
JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker,
null, null, Arrays.asList(source));
ct.parse();
if (diagChecker.errorFound) {
throw new Error("Unexpected parser error for source:\n" +
source.getCharContent(true));
}
}
示例8: compileAndCheck
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
void compileAndCheck(VarargsMethod m1, VarargsMethod m2, TypeKind actual, ArgumentsArity argsArity) throws Exception {
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
JavaSource source = new JavaSource(m1, m2, actual, argsArity);
ErrorChecker ec = new ErrorChecker();
JavacTask ct = (JavacTask)tool.getTask(null, fm, ec,
null, null, Arrays.asList(source));
ct.generate();
check(source, ec, m1, m2, actual, argsArity);
}
示例9: main
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
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));
}
示例10: main
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
public static void main(String[] args) throws IOException {
List<? extends JavaFileObject> files = Arrays.asList(new SourceFile());
JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, files);
Context ctx = new Context();
JavacFileManager.preRegister(ctx);
checkImplementationCache(ct.analyze(), Types.instance(ctx));
}
示例11: run
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
public boolean run() throws Util.Exit {
Util util = new Util(log, diagnosticListener);
if (noArgs || help) {
showHelp();
return help; // treat noArgs as an error for purposes of exit code
}
if (version || fullVersion) {
showVersion(fullVersion);
return true;
}
util.verbose = verbose;
Gen g;
if (llni)
g = new LLNI(doubleAlign, util);
else {
// if (stubs)
// throw new BadArgs("jni.no.stubs");
g = new JNI(util);
}
if (ofile != null) {
if (!(fileManager instanceof StandardJavaFileManager)) {
diagnosticListener.report(createDiagnostic("err.cant.use.option.for.fm", "-o"));
return false;
}
Iterable<? extends JavaFileObject> iter =
((StandardJavaFileManager) fileManager).getJavaFileObjectsFromFiles(Collections.singleton(ofile));
JavaFileObject fo = iter.iterator().next();
g.setOutFile(fo);
} else {
if (odir != null) {
if (!(fileManager instanceof StandardJavaFileManager)) {
diagnosticListener.report(createDiagnostic("err.cant.use.option.for.fm", "-d"));
return false;
}
if (!odir.exists())
if (!odir.mkdirs())
util.error("cant.create.dir", odir.toString());
try {
((StandardJavaFileManager) fileManager).setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(odir));
} catch (IOException e) {
Object msg = e.getLocalizedMessage();
if (msg == null) {
msg = e;
}
diagnosticListener.report(createDiagnostic("err.ioerror", odir, msg));
return false;
}
}
g.setFileManager(fileManager);
}
/*
* Force set to false will turn off smarts about checking file
* content before writing.
*/
g.setForce(force);
if (fileManager instanceof JavahFileManager)
((JavahFileManager) fileManager).setSymbolFileEnabled(false);
JavaCompiler c = ToolProvider.getSystemJavaCompiler();
List<String> opts = new ArrayList<String>();
opts.add("-proc:only");
opts.addAll(javac_extras);
CompilationTask t = c.getTask(log, fileManager, diagnosticListener, opts, classes, null);
JavahProcessor p = new JavahProcessor(g);
t.setProcessors(Collections.singleton(p));
boolean ok = t.call();
if (p.exit != null)
throw new Util.Exit(p.exit);
return ok;
}
示例12: main
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
write(test_java, test);
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager manager =
compiler.getStandardFileManager(null, null, null)) {
Iterable<? extends JavaFileObject> units = manager.getJavaFileObjects(test_java);
final StringWriter sw = new StringWriter();
JavacTask task = (JavacTask) compiler.getTask(sw, manager, null, null,
null, units);
new TreeScanner<Boolean, Void>() {
@Override
public Boolean visitClass(ClassTree arg0, Void arg1) {
sw.write(arg0.toString());
return super.visitClass(arg0, arg1);
}
}.scan(task.parse(), null);
System.out.println("output:");
System.out.println(sw.toString());
String found = sw.toString().replaceAll("\\s+", " ").trim();
String expect = test.replaceAll("\\s+", " ").trim();
if (!expect.equals(found)) {
System.out.println("expect: " + expect);
System.out.println("found: " + found);
throw new Exception("unexpected output");
}
}
}
示例13: test
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
private static void test(String classname, String expected) throws Exception {
File classfile = new File(System.getProperty("test.classes", "."), classname + ".class");
ClassFile cf = ClassFile.read(classfile);
cf = new ClassFile(cf.magic, Target.JDK1_7.minorVersion,
Target.JDK1_7.majorVersion, cf.constant_pool, cf.access_flags,
cf.this_class, cf.super_class, cf.interfaces, cf.fields,
cf.methods, cf.attributes);
new ClassWriter().write(cf, classfile);
JavaCompiler c = ToolProvider.getSystemJavaCompiler();
JavacTaskImpl task = (JavacTaskImpl) c.getTask(null, null, null, Arrays.asList("-classpath", System.getProperty("test.classes", ".")), null, null);
Symtab syms = Symtab.instance(task.getContext());
task.ensureEntered();
try {
Symbol clazz = com.sun.tools.javac.main.JavaCompiler.instance(task.getContext()).resolveIdent(syms.unnamedModule, classname);
clazz.complete();
} catch (BadClassFile f) {
JCDiagnostic embeddedDiag = (JCDiagnostic) f.diag.getArgs()[1];
assertEquals(expected, embeddedDiag.getCode());
assertEquals(Integer.toString(Target.JDK1_7.majorVersion), embeddedDiag.getArgs()[0]);
assertEquals(Integer.toString(Target.JDK1_7.minorVersion), embeddedDiag.getArgs()[1]);
}
}
示例14: run
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception {
JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker,
null, null, Arrays.asList(source));
try {
ct.analyze();
} catch (Throwable ex) {
fail("Error thrown when analyzing the following source:\n" + source.getCharContent(true));
}
check();
}
示例15: compile
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
/**
* Compiles sources with -XDrawDiagnostics flag and
* returns the output of compilation.
*
* @param sources sources
* @return the result of compilation
*/
private String compile(ToolBox.JavaSource...sources) {
JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
StringWriter writer = new StringWriter();
JavaCompiler.CompilationTask ct = jc.getTask(writer, null, null,
Arrays.asList("-XDrawDiagnostics"),
null, Arrays.asList(sources));
if (ct.call()) {
throw new RuntimeException("Expected compilation failure.");
}
return writer.toString().replace(ToolBox.lineSeparator, "\n");
}