本文整理汇总了Java中javax.tools.JavaCompiler.getStandardFileManager方法的典型用法代码示例。如果您正苦于以下问题:Java JavaCompiler.getStandardFileManager方法的具体用法?Java JavaCompiler.getStandardFileManager怎么用?Java JavaCompiler.getStandardFileManager使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.tools.JavaCompiler
的用法示例。
在下文中一共展示了JavaCompiler.getStandardFileManager方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: compileClass
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
/**
* Compile the provided class. The className may have a package separated by /. For example:
* my/package/myclass
*
* @param className Name of the class to compile.
* @param classCode Plain text contents of the class
* @return The byte contents of the compiled class.
* @throws IOException
*/
public byte[] compileClass(final String className, final String classCode) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
OutputStreamJavaFileManager<JavaFileManager> fileManager =
new OutputStreamJavaFileManager<JavaFileManager>(
javaCompiler.getStandardFileManager(null, null, null), byteArrayOutputStream);
List<JavaFileObject> fileObjects = new ArrayList<JavaFileObject>();
fileObjects.add(new JavaSourceFromString(className, classCode));
List<String> options = Arrays.asList("-classpath", this.classPath);
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
if (!javaCompiler.getTask(null, fileManager, diagnostics, options, null, fileObjects).call()) {
StringBuilder errorMsg = new StringBuilder();
for (Diagnostic d : diagnostics.getDiagnostics()) {
String err = String.format("Compilation error: Line %d - %s%n", d.getLineNumber(),
d.getMessage(null));
errorMsg.append(err);
System.err.print(err);
}
throw new IOException(errorMsg.toString());
}
return byteArrayOutputStream.toByteArray();
}
示例2: run
import javax.tools.JavaCompiler; //导入方法依赖的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());
}
}
}
示例3: testJavac
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
public void testJavac() throws Exception {
final JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
final StandardJavaFileManager fm = jc.getStandardFileManager(
null,
Locale.ENGLISH,
Charset.forName("UTF-8")); //NOI18N
fm.setLocation(
StandardLocation.CLASS_PATH,
Collections.singleton(FileUtil.archiveOrDirForURL(mvCp.entries().get(0).getURL())));
Iterable<JavaFileObject> res = fm.list(
StandardLocation.CLASS_PATH,
"", //NOI18N
EnumSet.of(JavaFileObject.Kind.CLASS),
true);
assertEquals(3, StreamSupport.stream(res.spliterator(), false).count());
}
示例4: compile
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
private void compile(String option, Path destDir, Path... files)
throws IOException
{
System.err.println("compile...");
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
Iterable<? extends JavaFileObject> fileObjects =
fm.getJavaFileObjectsFromPaths(Arrays.asList(files));
List<String> options = new ArrayList<>();
if (option != null) {
options.add(option);
}
if (destDir != null) {
options.add("-d");
options.add(destDir.toString());
}
options.add("-cp");
options.add(System.getProperty("test.classes", "."));
JavaCompiler.CompilationTask task =
compiler.getTask(null, fm, null, options, null, fileObjects);
if (!task.call())
throw new AssertionError("compilation failed");
}
}
示例5: getLocation_ISA
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
@Test
public void getLocation_ISA(Path base) throws Exception {
Path src1 = base.resolve("src1");
tb.writeJavaFiles(src1.resolve("m1x"), "module m1x { }", "package a; class A { }");
Path src2 = base.resolve("src2");
tb.writeJavaFiles(src2.resolve("m2x").resolve("extra"), "module m2x { }", "package b; class B { }");
Path modules = base.resolve("modules");
tb.createDirectories(modules);
String FS = File.separator;
String PS = File.pathSeparator;
JavaCompiler c = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager fm = c.getStandardFileManager(null, null, null)) {
fm.handleOption("--module-source-path",
List.of(src1 + PS + src2 + FS + "*" + FS + "extra").iterator());
try {
Iterable<? extends Path> paths = fm.getLocationAsPaths(StandardLocation.MODULE_SOURCE_PATH);
out.println("result: " + asList(paths));
throw new Exception("expected IllegalStateException not thrown");
} catch (IllegalStateException e) {
out.println("Exception thrown, as expected: " + e);
}
// even if we can't do getLocation for the MODULE_SOURCE_PATH, we should be able
// to do getLocation for the modules, which will additionally confirm the option
// was effective as intended.
Location locn1 = fm.getLocationForModule(StandardLocation.MODULE_SOURCE_PATH, "m1x");
checkLocation(fm.getLocationAsPaths(locn1), List.of(src1.resolve("m1x")));
Location locn2 = fm.getLocationForModule(StandardLocation.MODULE_SOURCE_PATH, "m2x");
checkLocation(fm.getLocationAsPaths(locn2), List.of(src2.resolve("m2x").resolve("extra")));
}
}
示例6: setLocation
import javax.tools.JavaCompiler; //导入方法依赖的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: compile
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
public static boolean compile(Path source, Path destination, String... options) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager jfm = compiler.getStandardFileManager(null, null, null)) {
List<Path> sources
= Files.find(source, Integer.MAX_VALUE,
(file, attrs) -> file.toString().endsWith(".java"))
.collect(Collectors.toList());
Files.createDirectories(destination);
jfm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT, Collections.singleton(destination));
List<String> opts = Arrays.asList(options);
JavaCompiler.CompilationTask task
= compiler.getTask(null, jfm, null, opts, null,
jfm.getJavaFileObjectsFromPaths(sources));
List<String> list = new ArrayList<>(opts);
list.addAll(sources.stream()
.map(Path::toString)
.collect(Collectors.toList()));
System.err.println("javac options: " + optionsPrettyPrint(list.toArray(new String[list.size()])));
return task.call();
}
}
示例8: compileModule
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
/**
* Compile the specified module from the given module sourcepath
*
* All warnings/errors emitted by the compiler are output to System.out/err.
*
* @return true if the compilation is successful
*
* @throws IOException if there is an I/O error scanning the source tree or
* creating the destination directory
*/
public static boolean compileModule(Path source, Path destination,
String moduleName, String... options) {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager jfm = compiler.getStandardFileManager(null, null, null);
try {
Files.createDirectories(destination);
jfm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT,
Arrays.asList(destination));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
Stream<String> opts = Arrays.stream(new String[] {
"--module-source-path", source.toString(), "-m", moduleName
});
List<String> javacOpts = Stream.concat(opts, Arrays.stream(options))
.collect(Collectors.toList());
JavaCompiler.CompilationTask task
= compiler.getTask(null, jfm, null, javacOpts, null, null);
return task.call();
}
示例9: compile
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
public void compile(JavaCompiler javaCompiler, Writer out, File sourceDirectory, File outputDirectory, List<File> classpath, DiagnosticListener<? super JavaFileObject> diagnosticListener, String targetVersion ) {
targetVersion = targetVersion == null ? "1.6" : targetVersion;
StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, null, null);
if (outputDirectory != null) {
try {
fileManager.setLocation(StandardLocation.CLASS_OUTPUT,
Arrays.asList(outputDirectory));
fileManager.setLocation(StandardLocation.CLASS_PATH, classpath);
} catch (IOException e) {
throw new RuntimeException("could not set output directory", e);
}
}
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(findAllSourceFiles(sourceDirectory));
ArrayList<String> options = new ArrayList<String>();
options.add("-source");
options.add(targetVersion);
options.add("-target");
options.add(targetVersion);
options.add("-encoding");
options.add("UTF8");
options.add("-Xlint:-options");
options.add("-Xlint:unchecked");
if (compilationUnits.iterator().hasNext()) {
Boolean success = javaCompiler.getTask(out, fileManager, diagnosticListener, options, null, compilationUnits).call();
assertThat("Compilation was not successful, check stdout for errors", success, is(true));
}
}
示例10: main
import javax.tools.JavaCompiler; //导入方法依赖的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 (CastKind ck : CastKind.values()) {
for (TypeKind t1 : TypeKind.values()) {
for (ArrayKind ak1 : ArrayKind.values()) {
Type typ1 = new Type(t1, ak1);
if (ck.nBounds == 1) {
new IntersectionTypeParserTest(ck, typ1).run(comp, fm);
continue;
}
for (TypeKind t2 : TypeKind.values()) {
for (ArrayKind ak2 : ArrayKind.values()) {
Type typ2 = new Type(t2, ak2);
if (ck.nBounds == 2) {
new IntersectionTypeParserTest(ck, typ1, typ2).run(comp, fm);
continue;
}
for (TypeKind t3 : TypeKind.values()) {
for (ArrayKind ak3 : ArrayKind.values()) {
Type typ3 = new Type(t3, ak3);
new IntersectionTypeParserTest(ck, typ1, typ2, typ3).run(comp, fm);
}
}
}
}
}
}
}
System.out.println("Total check executed: " + checkCount);
}
}
示例11: main
import javax.tools.JavaCompiler; //导入方法依赖的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 (CastInfo cInfo : allCastInfo()) {
for (ExpressionKind ek : ExpressionKind.values()) {
new IntersectionTargetTypeTest(cInfo, ek).run(comp, fm);
}
}
System.out.println("Total check executed: " + checkCount);
}
}
示例12: compile
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
private static void compile(List<String> options, Iterable<File> files) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager mgr = compiler.getStandardFileManager(null, null, null);
List<String> fullOptions = new ArrayList<String>(options);
fullOptions.addAll(Arrays.asList("-source", "1.5", "-target", "1.5"));
if (!compiler.getTask(null, mgr, null, fullOptions, null, mgr.getJavaFileObjectsFromFiles(files)).call()) {
throw new IOException("compilation failed");
}
}
示例13: compile
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
/**
* Compile all the java sources in {@code <source>/**} to
* {@code <destination>/**}. The destination directory will be created if
* it doesn't exist.
*
* All warnings/errors emitted by the compiler are output to System.out/err.
*
* @return true if the compilation is successful
*
* @throws IOException
* if there is an I/O error scanning the source tree or
* creating the destination directory
* @throws UnsupportedOperationException
* if there is no system java compiler
*/
public static boolean compile(Path source, Path destination, String... options)
throws IOException
{
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null) {
// no compiler available
throw new UnsupportedOperationException("Unable to get system java compiler. "
+ "Perhaps, jdk.compiler module is not available.");
}
StandardJavaFileManager jfm = compiler.getStandardFileManager(null, null, null);
List<Path> sources
= Files.find(source, Integer.MAX_VALUE,
(file, attrs) -> (file.toString().endsWith(".java")))
.collect(Collectors.toList());
Files.createDirectories(destination);
jfm.setLocation(StandardLocation.CLASS_PATH, Collections.emptyList());
jfm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT,
Collections.singletonList(destination));
List<String> opts = Arrays.asList(options);
JavaCompiler.CompilationTask task
= compiler.getTask(null, jfm, null, opts, null,
jfm.getJavaFileObjectsFromPaths(sources));
return task.call();
}
示例14: getPreviewProvider
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
public static IPreviewProvider getPreviewProvider(File sourceFile) {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
File tmpDir = new File(System.getProperty("java.io.tmpdir"));
try (StandardJavaFileManager fileManager = compiler
.getStandardFileManager(null, null, null)) {
Iterable javaFiles = fileManager.getJavaFileObjects(sourceFile);
fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(tmpDir));
List<String> options = Arrays.asList("-d", tmpDir.getAbsolutePath());
compiler.getTask(null, fileManager, null, null, null, javaFiles)
.call();
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Error during runtime compilation", e);
}
try {
URL[] urls = new URL[]{new URL("file://" + tmpDir + "/")};
System.out.println(urls[0].toString());
URLClassLoader ucl = new URLClassLoader(urls);
Class clazz = ucl.loadClass("pl.gda.pg.eti.kernelhive.gui.component.workflow.preview.PreviewProvider");
System.out.println("Class has been successfully loaded");
IPreviewProvider provider = (IPreviewProvider) clazz.newInstance();
return provider;
} catch (MalformedURLException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
Logger.getLogger(RuntimeClassFactory.class.getName())
.log(Level.SEVERE, "Error while creating PreviewProider", ex);
return null;
}
}
示例15: main
import javax.tools.JavaCompiler; //导入方法依赖的package包/类
public static void main(String[] args) {
System.out.println("Sourcepath is " + args[0]);
// We're interested in scanning all .java files under the sourcepath passed as an argument here.
List<File> sourceFiles = Arrays.asList(new File(new File(args[0]).getAbsolutePath()).listFiles(f -> f.getName().endsWith(".java")));
sourceFiles.stream().forEach(System.out::println); // Printing the detected class file paths.
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> javaFileObjects = fileManager.getJavaFileObjectsFromFiles(sourceFiles);
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null, javaFileObjects);
task.setProcessors(Arrays.asList(new PrivateOnlyAnnotationProcessor(), new JavaBeanAnnotationProcessor()));
System.out.println(task.call());
}