本文整理汇总了Java中javax.tools.JavaCompiler.CompilationTask.setProcessors方法的典型用法代码示例。如果您正苦于以下问题:Java CompilationTask.setProcessors方法的具体用法?Java CompilationTask.setProcessors怎么用?Java CompilationTask.setProcessors使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.tools.JavaCompiler.CompilationTask
的用法示例。
在下文中一共展示了CompilationTask.setProcessors方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testSingleSourceDir
import javax.tools.JavaCompiler.CompilationTask; //导入方法依赖的package包/类
private void testSingleSourceDir(JavaCompiler javac) throws Exception {
System.err.println("testSingleSourceDir");
File tmpdir = new File("testSingleSourceDir");
File srcdir = new File(tmpdir, "src");
File destdir = new File(tmpdir, "dest");
write(srcdir, "pkg/X.java", "package pkg; class X {}");
write(srcdir, "resources/file.txt", "hello");
destdir.mkdirs();
CompilationTask task = javac.getTask(null, null, null,
Arrays.asList("-sourcepath", srcdir.toString(), "-d", destdir.toString()),
Collections.singleton("pkg.X"), null);
task.setProcessors(Collections.singleton(new AnnoProc()));
boolean result = task.call();
System.err.println("javac result with single source dir: " + result);
expect(result, true);
}
示例2: testCompositeSourcePath
import javax.tools.JavaCompiler.CompilationTask; //导入方法依赖的package包/类
private void testCompositeSourcePath(JavaCompiler javac) throws Exception {
System.err.println("testCompositeSearchPath");
File tmpdir = new File("testCompositeSourcePath");
File srcdir = new File(tmpdir, "src");
File rsrcdir = new File(tmpdir, "rsrc");
File destdir = new File(tmpdir, "dest");
write(srcdir, "pkg/X.java", "package pkg; class X {}");
write(rsrcdir, "resources/file.txt", "hello");
destdir.mkdirs();
CompilationTask task = javac.getTask(null, null, null,
Arrays.asList("-sourcepath", srcdir + File.pathSeparator + rsrcdir, "-d", destdir.toString()),
Collections.singleton("pkg.X"), null);
task.setProcessors(Collections.singleton(new AnnoProc()));
boolean result = task.call();
System.err.println("javac result with composite source path: " + result);
expect(result, true);
}
示例3: testMissingResource
import javax.tools.JavaCompiler.CompilationTask; //导入方法依赖的package包/类
private void testMissingResource(JavaCompiler javac) throws Exception {
System.err.println("testMissingResource");
File tmpdir = new File("testMissingResource");
File srcdir = new File(tmpdir, "src");
File destdir = new File(tmpdir, "dest");
write(srcdir, "pkg/X.java", "package pkg; class X {}");
destdir.mkdirs();
CompilationTask task = javac.getTask(null, null, null,
Arrays.asList("-sourcepath", srcdir.toString(), "-d", destdir.toString()),
Collections.singleton("pkg.X"), null);
task.setProcessors(Collections.singleton(new AnnoProc()));
boolean result = task.call();
System.err.println("javac result when missing resource: " + result);
expect(result, false);
if (errors > 0)
throw new Exception(errors + " errors occurred");
}
示例4: run
import javax.tools.JavaCompiler.CompilationTask; //导入方法依赖的package包/类
void run() throws Exception {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
System.err.println("using " + compiler.getClass()
+ " from " + compiler.getClass().getProtectionDomain().getCodeSource());
CompilationTask task = compiler.getTask(null, null, null,
Collections.singleton("-proc:only"),
Collections.singleton("java.lang.Object"),
null);
task.setProcessors(Collections.singleton(new Proc()));
check("compilation", task.call());
task = compiler.getTask(null, null, null,
Arrays.asList("-proc:only", "-AexpectFile"),
Collections.singleton("java.lang.Object"),
null);
task.setProcessors(Collections.singleton(new Proc()));
check("compilation", task.call());
}
示例5: compile
import javax.tools.JavaCompiler.CompilationTask; //导入方法依赖的package包/类
/** Convenient JavaCompiler facade returning a ClassLoader with all compiled units. */
static ClassLoader compile(
ClassLoader parent,
List<String> options,
List<Processor> processors,
List<JavaFileObject> units) {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
Objects.requireNonNull(compiler, "no system java compiler available - JDK is required!");
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
StandardJavaFileManager sjfm =
compiler.getStandardFileManager(diagnostics, Locale.getDefault(), StandardCharsets.UTF_8);
Manager manager = new Manager(sjfm, parent);
CompilationTask task = compiler.getTask(null, manager, diagnostics, options, null, units);
if (!processors.isEmpty()) {
task.setProcessors(processors);
}
boolean success = task.call();
if (!success) {
throw new RuntimeException("compilation failed! " + diagnostics.getDiagnostics());
}
return manager.getClassLoader(StandardLocation.CLASS_PATH);
}
示例6: run
import javax.tools.JavaCompiler.CompilationTask; //导入方法依赖的package包/类
public Result run(
String[] args,
JavaFileManager fileManager,
List<JavaFileObject> javaFileObjects,
Iterable<? extends Processor> processors) {
JavaCompiler compiler = new BaseErrorProneJavaCompiler(scannerSupplier);
try {
CompilationTask task =
compiler.getTask(
errOutput,
fileManager,
diagnosticListener,
ImmutableList.copyOf(args),
null /*classes*/,
javaFileObjects);
if (processors != null) {
task.setProcessors(processors);
}
return task.call() ? Result.OK : Result.ERROR;
} catch (InvalidCommandLineOptionException e) {
errOutput.print(e);
errOutput.flush();
return Result.CMDERR;
}
}
示例7: testProcessingEnvironmentLeak
import javax.tools.JavaCompiler.CompilationTask; //导入方法依赖的package包/类
public void testProcessingEnvironmentLeak() throws Exception { // #198604
try {
if (Modifier.isStatic(Class.forName("com.sun.tools.javac.code.Symtab").getField("byteType").getModifiers())) {
System.err.println("Skipping testProcessingEnvironmentLeak due to old buggy version of javac");
return;
}
} catch (Exception x) {
System.err.println("Note: perhaps using non-javac compiler? " + x);
}
clearWorkDir();
File src = new File(getWorkDir(), "src");
AnnotationProcessorTestUtils.makeSource(src, "p.C", "@" + A.class.getCanonicalName() + " public class C {}");
File dest = new File(getWorkDir(), "dest");
assertTrue(dest.mkdirs());
List<String> args = new ArrayList<String>();
args.add("-classpath");
args.add(dest + File.pathSeparator + System.getProperty("java.class.path"));
args.add("-d");
args.add(dest.getAbsolutePath());
args.add("-sourcepath");
args.add(src.getAbsolutePath());
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
JavaFileManager fm = compiler.getStandardFileManager(null, null, null);
CompilationTask task = compiler.getTask(null, fm, null, args, Collections.singleton("p.C"), null);
P p = new P();
task.setProcessors(Collections.singleton(p));
assertFalse(task.call());
assertNotNull(p.env);
Reference<?> r = new WeakReference<Object>(p.env);
compiler = null;
fm = null;
task = null;
p = null;
assertGC("can collect ProcessingEnvironment", r);
}
示例8: run
import javax.tools.JavaCompiler.CompilationTask; //导入方法依赖的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;
}
示例9: beforeEachTest
import javax.tools.JavaCompiler.CompilationTask; //导入方法依赖的package包/类
@Before
public void beforeEachTest() throws MalformedURLException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
JavaFileObject input = JavaFileObjects.forResource("input/IntegrationTestHelper.java");
// compile source code from resources and put the output classfiles in a temporary directory
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
CompilationTask task = compiler.getTask(
null,
null,
null,
asList("-d", tmpFolder.getRoot().toString()),
null,
singletonList(input)
);
task.setProcessors(singletonList(new AutoValueProcessor()));
boolean success = task.call();
if (!success) {
throw new RuntimeException("Couldn't compile the input data for test!");
}
// load the generated classfiles
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { tmpFolder.getRoot().toURI().toURL() });
Class<?> integrationClass = Class.forName("test.AutoValue_IntegrationTestHelper", true, classLoader);
Class<?> captorClass = Class.forName("test.IntegrationTestHelper$HashCodeCaptor", true, classLoader);
hashCodeCallsCaptor = invokeConstructor(captorClass);
// AutoValues constructor is package private, and it's probably the easiest way to create the class
Constructor<?> declaredConstructor = integrationClass.getDeclaredConstructor(captorClass);
declaredConstructor.setAccessible(true);
integrationTestHelper = declaredConstructor.newInstance(hashCodeCallsCaptor);
}
示例10: compile
import javax.tools.JavaCompiler.CompilationTask; //导入方法依赖的package包/类
static Result compile(ClassLoader loader, Iterable<Processor> processors,
Iterable<String> options, JavaFileObject... objects) {
// we need all this because we got a annotation processor, the generated
// class has to go into memory too
final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
InMemoryJavaFileManager fileManager = new InMemoryJavaFileManager(
compiler.getStandardFileManager(diagnosticCollector, Locale.getDefault(), UTF_8),
loader);
CompilationTask task = compiler.getTask(null, fileManager, diagnosticCollector, options,
null, Arrays.asList(objects));
task.setProcessors(processors);
Exception exception = null;
try {
if (!task.call())
throw new RuntimeException("File compiled with error, the cause is unknown");
} catch (Exception e) {
exception = e;
}
System.out.println(printVertically(diagnosticCollector.getDiagnostics()));
return new Result(fileManager.getClassLoader(StandardLocation.CLASS_OUTPUT),
fileManager.getOutputFiles(),
exception == null ? null
: new RuntimeException(
"Compilation failed:\n"
+ printVertically(diagnosticCollector.getDiagnostics()),
exception));
}
示例11: run
import javax.tools.JavaCompiler.CompilationTask; //导入方法依赖的package包/类
@Override
public void run() {
TempJavaFileManager fileManager = TempJavaFileManager.newTempFileManager(null, null, null);
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
try {
final JavaFileObject bootstrapType = new SourceBuilder()
.addLine("package %s;", PACKAGE)
.addLine("@%s", Target.class)
.addLine("class %s { }", PLACEHOLDER_TYPE)
.build();
CompilationTask task = getSystemJavaCompiler().getTask(
null, // Writer
fileManager,
diagnostics,
ImmutableList.of("-proc:only", "-encoding", "UTF-8"),
null, // Class names
ImmutableList.of(bootstrapType));
task.setProcessors(ImmutableList.of(new ElementCapturingProcessor()));
task.call();
} catch (RuntimeException e) {
processingEnvFuture.setException(e);
elementFuture.setException(e);
} finally {
if (!processingEnvFuture.isDone()) {
processingEnvFuture.setException(new CompilationException(diagnostics.getDiagnostics()));
}
if (!elementFuture.isDone()) {
if (diagnostics.getDiagnostics().isEmpty()) {
elementFuture.setException(new IllegalStateException(
"Code generation terminated abnormally. Was there no annotated element?"));
} else {
elementFuture.setException(new CompilationException(diagnostics.getDiagnostics()));
}
}
fileManager.close();
}
}
示例12: compile
import javax.tools.JavaCompiler.CompilationTask; //导入方法依赖的package包/类
private static ImmutableList<Diagnostic<? extends JavaFileObject>> compile(
JavaFileManager fileManager,
Iterable<? extends JavaFileObject> compilationUnits,
Iterable<? extends Processor> processors,
SourceLevel sourceLevel) {
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
List<String> arguments = ImmutableList.<String>builder()
.add("-Xlint:unchecked")
.add("-Xlint:varargs")
.add("-Xdiags:verbose")
.addAll(sourceLevel.javacArguments())
.build();
CompilationTask task = getCompiler().getTask(
null,
fileManager,
diagnostics,
arguments,
null,
compilationUnits);
task.setProcessors(processors);
boolean successful = task.call();
if (!successful) {
throw new CompilationException(diagnostics.getDiagnostics());
}
// Filter out any errors: if compilation succeeded, they're probably "cannot find symbol"
// errors erroneously emitted by the compiler prior to running annotation processing.
return FluentIterable.from(diagnostics.getDiagnostics())
.filter(not(Diagnostics.isKind(Diagnostic.Kind.ERROR)))
.toList();
}
示例13: compile
import javax.tools.JavaCompiler.CompilationTask; //导入方法依赖的package包/类
/**
* Compile a unit of source code with the specified annotation processor
* @param annotationProcessor
* @param compilationUnits
* @return
*/
public List<Diagnostic<? extends JavaFileObject>> compile(final Processor annotationProcessor,
final String... compilationUnits) {
final DiagnosticCollector<JavaFileObject> diagnosticListener = new DiagnosticCollector<JavaFileObject>();
try {
final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
final StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticListener,
null,
null);
String[] convertedCompilationUnits = convertCompilationUnitToFilePaths(compilationUnits);
final Iterable<? extends JavaFileObject> compilationUnitsJavaObjects =
fileManager.getJavaFileObjects(convertedCompilationUnits);
//Compile with provide annotation processor
final CompilationTask task = compiler.getTask(null,
fileManager,
diagnosticListener,
null,
null,
compilationUnitsJavaObjects);
task.setProcessors(Arrays.asList(annotationProcessor));
task.call();
fileManager.close();
} catch (IOException ioe) {
fail(ioe.getMessage());
}
return diagnosticListener.getDiagnostics();
}
示例14: compile
import javax.tools.JavaCompiler.CompilationTask; //导入方法依赖的package包/类
/**
* Compile a unit of source code with the specified annotation processor
* @param annotationProcessor
* @param compilationUnits
* @return
*/
public List<Diagnostic<? extends JavaFileObject>> compile(final Processor annotationProcessor,
final String... compilationUnits) {
final DiagnosticCollector<JavaFileObject> diagnosticListener = new DiagnosticCollector<JavaFileObject>();
try {
final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
final StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticListener,
null,
null);
String[] convertedCompilationUnits = convertCompilationUnitToFilePaths(compilationUnits);
final Iterable<? extends JavaFileObject> compilationUnitsJavaObjects =
fileManager.getJavaFileObjects(convertedCompilationUnits);
//Compile with provide annotation processor
final CompilationTask task = compiler.getTask(null,
fileManager,
diagnosticListener,
null,
null,
compilationUnitsJavaObjects);
task.setProcessors(Arrays.asList(annotationProcessor));
task.call();
fileManager.close();
} catch (IOException ioe) {
fail(ioe.getMessage());
}
return diagnosticListener.getDiagnostics().stream().filter(p -> p.getKind() != Kind.NOTE).collect(Collectors.toList());
}
示例15: processAndCompile
import javax.tools.JavaCompiler.CompilationTask; //导入方法依赖的package包/类
/**
* Generated the meta classes before the given {@code domainClass} is compiled.
*
* @param domainClass the domain class with relevant annotations
* @throws IOException if location is an output location and path does not represent an existing
* directory
*/
private void processAndCompile(final List<Class<?>> domainClasses) throws IOException {
// configuration
final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
final CompilationDiagnosticListener diagnosticListener = new CompilationDiagnosticListener();
final StandardJavaFileManager fileManager =
compiler.getStandardFileManager(diagnosticListener, null, null);
fileManager.setLocation(SOURCE_OUTPUT, Arrays.asList(TARGET_GENERATED_TEST_SOURCES_FOLDER));
fileManager.setLocation(CLASS_OUTPUT, Arrays.asList(TARGET_TEST_CLASSES_FOLDER));
final List<File> domainSourceFiles = new ArrayList<>();
for (Class<?> domainClass : domainClasses) {
final String domainSourceFileName =
domainClass.getName().replace(".", File.separator) + ".java";
final File domainSourceFile = new File(SRC_TEST_JAVA_FOLDER, domainSourceFileName);
assertThat(domainSourceFile).exists();
domainSourceFiles.add(domainSourceFile);
}
final Iterable<? extends JavaFileObject> filesToCompile =
fileManager.getJavaFileObjectsFromFiles(domainSourceFiles);
final CompilationTask basicCompilationTask =
compiler.getTask(null, fileManager, diagnosticListener, null, null, filesToCompile);
final Boolean compiledWithoutErrors = basicCompilationTask.call();
final List<String> options = Arrays.asList("-proc:none");
final CompilationTask aptCompilationTask =
compiler.getTask(null, fileManager, diagnosticListener, options, null, filesToCompile);
aptCompilationTask.setProcessors(Arrays.asList(new DocumentAnnotationProcessor(),
new EmbeddedDocumentAnnotationProcessor()));
// operation
// final Boolean compiledWithoutErrors = aptCompilationTask.call();
assertThat(compiledWithoutErrors).as("Files compiled without errors").isTrue();
}