本文整理汇总了Java中javax.tools.ToolProvider.getSystemJavaCompiler方法的典型用法代码示例。如果您正苦于以下问题:Java ToolProvider.getSystemJavaCompiler方法的具体用法?Java ToolProvider.getSystemJavaCompiler怎么用?Java ToolProvider.getSystemJavaCompiler使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.tools.ToolProvider
的用法示例。
在下文中一共展示了ToolProvider.getSystemJavaCompiler方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: run
import javax.tools.ToolProvider; //导入方法依赖的package包/类
void run() throws IOException {
String lineSep = System.getProperty("line.separator");
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
StringWriter out = new StringWriter();
PrintWriter outWriter = new PrintWriter(out)) {
Iterable<? extends JavaFileObject> input =
fm.getJavaFileObjects(System.getProperty("test.src") + "/ReleaseOption.java");
List<String> options = Arrays.asList("--release", "7", "-XDrawDiagnostics");
compiler.getTask(outWriter, fm, null, options, null, input).call();
String expected =
"ReleaseOption.java:9:49: compiler.err.doesnt.exist: java.util.stream" + lineSep +
"1 error" + lineSep;
if (!expected.equals(out.toString())) {
throw new AssertionError("Unexpected output: " + out.toString());
}
}
}
示例2: javac
import javax.tools.ToolProvider; //导入方法依赖的package包/类
static void javac(Path dest, List<Path> sourceFiles) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager fileManager =
compiler.getStandardFileManager(null, null, null)) {
List<File> files = sourceFiles.stream()
.map(p -> p.toFile())
.collect(Collectors.toList());
Iterable<? extends JavaFileObject> compilationUnits =
fileManager.getJavaFileObjectsFromFiles(files);
fileManager.setLocation(StandardLocation.CLASS_OUTPUT,
Arrays.asList(dest.toFile()));
fileManager.setLocation(StandardLocation.CLASS_PATH,
Arrays.asList(TEST_CLASSES.toFile()));
JavaCompiler.CompilationTask task = compiler
.getTask(null, fileManager, null, null, null, compilationUnits);
boolean passed = task.call();
if (!passed)
throw new RuntimeException("Error compiling " + files);
}
}
示例3: loadBadClass
import javax.tools.ToolProvider; //导入方法依赖的package包/类
private static BadClassFile loadBadClass(String className) {
// load the class, and save the thrown BadClassFile exception
JavaCompiler c = ToolProvider.getSystemJavaCompiler();
JavacTaskImpl task = (JavacTaskImpl) c.getTask(null, null, null,
Arrays.asList("-classpath", classesdir.getPath()), null, null);
Symtab syms = Symtab.instance(task.getContext());
task.ensureEntered();
BadClassFile badClassFile;
try {
com.sun.tools.javac.main.JavaCompiler.instance(task.getContext())
.resolveIdent(syms.unnamedModule, className).complete();
} catch (BadClassFile e) {
return e;
}
return null;
}
示例4: parse
import javax.tools.ToolProvider; //导入方法依赖的package包/类
static List<? extends Tree> parse(String srcfile) throws Exception {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> fileObjects = fileManager.getJavaFileObjects(srcfile);
String classPath = System.getProperty("java.class.path");
List<String> options = Arrays.asList("-classpath", classPath);
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
Context context = new Context();
JavacTaskImpl task = (JavacTaskImpl) ((JavacTool) compiler).getTask(null, null,
diagnostics, options, null, fileObjects, context);
TrialParserFactory.instance(context);
Iterable<? extends CompilationUnitTree> asts = task.parse();
Iterator<? extends CompilationUnitTree> it = asts.iterator();
if (it.hasNext()) {
CompilationUnitTree cut = it.next();
return cut.getTypeDecls();
} else {
throw new AssertionError("Expected compilation unit");
}
}
示例5: testModuleSymbolOutterMostClass
import javax.tools.ToolProvider; //导入方法依赖的package包/类
@Test
public void testModuleSymbolOutterMostClass(Path base) throws Exception {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
Path moduleSrc = base.resolve("module-src");
Path m1 = moduleSrc.resolve("m1x");
tb.writeJavaFiles(m1, "module m1x { }");
Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(findJavaFiles(moduleSrc));
com.sun.source.util.JavacTask task =
(com.sun.source.util.JavacTask) compiler.getTask(null, fm, null, null, null, files);
task.analyze();
ModuleSymbol msym = (ModuleSymbol) task.getElements().getModuleElement("m1x");
msym.outermostClass();
}
}
示例6: setLocation
import javax.tools.ToolProvider; //导入方法依赖的package包/类
@Test
public void setLocation(Path base) throws Exception {
Path src = base.resolve("src");
tb.writeJavaFiles(src.resolve("m1x"), "module m1x { }", "package a; class A { }");
Path modules = base.resolve("modules");
tb.createDirectories(modules);
JavaCompiler c = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager fm = c.getStandardFileManager(null, null, null)) {
fm.setLocationFromPaths(StandardLocation.MODULE_SOURCE_PATH, List.of(src));
new JavacTask(tb)
.options("-XDrawDiagnostics")
.fileManager(fm)
.outdir(modules)
.files(findJavaFiles(src))
.run()
.writeAll();
checkFiles(modules.resolve("m1x/module-info.class"), modules.resolve("m1x/a/A.class"));
}
}
示例7: main
import javax.tools.ToolProvider; //导入方法依赖的package包/类
public static void main(String... args) throws Exception {
//create default shared JavaCompiler - reused across multiple compilations
JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {
for (EnclosingKind ek : EnclosingKind.values()) {
for (SiteKind sk : SiteKind.values()) {
if (sk == SiteKind.STATIC_INIT && ek == EnclosingKind.MEMBER_INNER)
continue;
for (InnerKind ik : InnerKind.values()) {
if (ik != InnerKind.NONE && sk == SiteKind.NONE)
break;
for (RefKind rk : RefKind.values()) {
new TestSelfRef(ek, sk, ik, rk).run(comp, fm);
}
}
}
}
System.out.println("Total check executed: " + checkCount);
}
}
示例8: compile
import javax.tools.ToolProvider; //导入方法依赖的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");
}
}
}
}
示例9: main
import javax.tools.ToolProvider; //导入方法依赖的package包/类
public static void main(String... args) throws IOException {
if (args.length != 1) {
System.err.println("Not enough arguments.");
System.err.println("Usage:");
System.err.println(" java " + Probe.class.getName() + " <output-file>");
return ;
}
File outFile = new File(args[0]);
Charset cs = Charset.forName("UTF-8");
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
OutputStream out = new FileOutputStream(outFile);
try {
Iterable<JavaFileObject> bcpFiles =
fm.list(StandardLocation.PLATFORM_CLASS_PATH, "", EnumSet.of(Kind.CLASS), true);
for (JavaFileObject jfo : bcpFiles) {
InputStream in = new BufferedInputStream(jfo.openInputStream());
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
StringBuilder textual = new StringBuilder();
int read;
while ((read = in.read()) != (-1)) {
baos.write(read);
textual.append(String.format("%02x", read));
}
textual.append("\n");
out.write(textual.toString().getBytes(cs));
} finally {
in.close();
}
}
} finally {
out.close();
}
}
示例10: compileAndCheck
import javax.tools.ToolProvider; //导入方法依赖的package包/类
void compileAndCheck() throws Exception {
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
JavaSource source = new JavaSource();
JavacTask ct = (JavacTask)tool.getTask(null, fm, null,
null, null, Arrays.asList(source));
ct.call();
verifyBytecode(source);
}
示例11: testThroughFormatterFormat
import javax.tools.ToolProvider; //导入方法依赖的package包/类
public void testThroughFormatterFormat() throws IOException {
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
DiagnosticChecker dc = new DiagnosticChecker("compiler.err.prob.found.req");
JavacTask ct = (JavacTask)tool.getTask(null, null, dc, null, null, Arrays.asList(new JavaSource()));
ct.analyze();
DiagnosticFormatter<JCDiagnostic> formatter =
Log.instance(((JavacTaskImpl) ct).getContext()).getDiagnosticFormatter();
String msg = formatter.formatMessage(dc.diag, Locale.getDefault());
//no redundant package qualifiers
Assert.check(msg.indexOf("java.") == -1, msg);
}
示例12: main
import javax.tools.ToolProvider; //导入方法依赖的package包/类
public static void main(String... args) {
javax.tools.JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
JavacTaskImpl task = (JavacTaskImpl)tool.getTask(null, null, null, null, null, null);
Symtab syms = Symtab.instance(task.getContext());
task.ensureEntered();
JavaCompiler compiler = JavaCompiler.instance(task.getContext());
try {
compiler.resolveIdent(syms.unnamedModule, "Test$1").complete();
} catch (CompletionFailure ex) {
System.err.println("Got expected completion failure: " + ex.getLocalizedMessage());
return;
}
throw new AssertionError("No error reported");
}
示例13: run
import javax.tools.ToolProvider; //导入方法依赖的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;
}
示例14: compile
import javax.tools.ToolProvider; //导入方法依赖的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");
}
示例15: testUnnamed
import javax.tools.ToolProvider; //导入方法依赖的package包/类
@Test
public void testUnnamed(Path base) throws Exception {
Path moduleSrc = base.resolve("module-src");
Path m1 = moduleSrc.resolve("m1x");
tb.writeJavaFiles(m1,
"module m1x { exports m1x; }",
"package m1x; public class M1 {}");
Path m2 = moduleSrc.resolve("m2x");
tb.writeJavaFiles(m2,
"module m2x { exports m2x; }",
"package m2x; public class M2 {}");
Path modulePath = base.resolve("module-path");
Files.createDirectories(modulePath);
new JavacTask(tb)
.options("--module-source-path", moduleSrc.toString())
.outdir(modulePath)
.files(findJavaFiles(moduleSrc))
.run()
.writeAll();
Path cpSrc = base.resolve("cp-src");
tb.writeJavaFiles(cpSrc,
"package cp; public class CP {}");
Path cp = base.resolve("cp");
Files.createDirectories(cp);
new JavacTask(tb)
.outdir(cp)
.files(findJavaFiles(cpSrc))
.run()
.writeAll();
Path src = base.resolve("src");
tb.writeJavaFiles(src,
"package test; public class Test1 {}",
"package test; public class Test2 {}");
Path out = base.resolve("out");
Files.createDirectories(out);
JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager fm = javaCompiler.getStandardFileManager(null, null, null)) {
com.sun.source.util.JavacTask task =
(com.sun.source.util.JavacTask) javaCompiler.getTask(null,
null,
d -> { throw new IllegalStateException(d.toString()); },
Arrays.asList("--module-path", modulePath.toString(),
"--class-path", cp.toString(),
"-sourcepath", src.toString()),
null,
fm.getJavaFileObjects(src.resolve("test").resolve("Test2.java")));
assertNotNull(task.getElements().getTypeElement("java.lang.String"));
assertNotNull(task.getElements().getTypeElement("javax.tools.ToolProvider"));
assertNull(task.getElements().getTypeElement("m1x.M1"));
assertNull(task.getElements().getTypeElement("m2x.M2"));
assertNotNull(task.getElements().getTypeElement("cp.CP"));
assertNotNull(task.getElements().getTypeElement("test.Test1"));
assertNotNull(task.getElements().getTypeElement("test.Test2"));
assertNotNull(task.getElements().getModuleElement("java.base"));
assertNotNull(task.getElements().getModuleElement("java.compiler"));
assertNull(task.getElements().getModuleElement("m1x"));
assertNull(task.getElements().getModuleElement("m2x"));
}
}