下面列出了怎么用javax.tools.JavaFileObject.Kind的API类实例代码及写法,或者点击链接到github查看源代码。
public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException {
if (Kind.CLASS != kind && Kind.SOURCE != kind)
throw new IOException("Unsupported output kind: " + kind);
if (!(location instanceof StandardLocation))
throw new IOException("Unsupported output location: " + location);
switch ((StandardLocation) location) {
case CLASS_OUTPUT:
return getOrCreateMemFileByClassName(className, this.classes, JavaClassFile.class);
case SOURCE_OUTPUT:
return getOrCreateMemFileByClassName(className, this.srcs, JavaSourceFile.class);
case CLASS_PATH:
case SOURCE_PATH:
case ANNOTATION_PROCESSOR_PATH:
case PLATFORM_CLASS_PATH:
default:
throw new IOException("Unsupported output location: " + location);
}
}
@Override
public Iterable<JavaFileObject> list(Location location,
String packageName, Set<Kind> kinds, boolean recurse)
throws IOException {
// validatePackageName(packageName);
nullCheck(packageName);
nullCheck(kinds);
Iterable<? extends Path> paths = getLocation(location);
if (paths == null)
return List.nil();
ListBuffer<JavaFileObject> results = new ListBuffer<JavaFileObject>();
for (Path path : paths)
list(path, packageName, kinds, recurse, results);
return results.toList();
}
@Override
public Iterable<JavaFileObject> list(Location location, String packageName, Set<Kind> kinds, boolean recurse)
throws IOException {
Iterable<? extends File> allFilesInLocations = getLocation(location);
if (allFilesInLocations == null) {
throw new IllegalArgumentException("Unknown location : " + location);//$NON-NLS-1$
}
ArrayList<JavaFileObject> collector = new ArrayList<JavaFileObject>();
String normalizedPackageName = normalized(packageName);
for (File file : allFilesInLocations) {
collectAllMatchingFiles(file, normalizedPackageName, kinds, recurse, collector);
}
return collector;
}
@Override
public Iterable<JavaFileObject> list(Location location,
String packageName,
Set<Kind> kinds,
boolean recurse)
throws IOException
{
// Acquire the list of files.
Iterable<JavaFileObject> files = super.list(location, packageName, kinds, recurse);
if (visibleSources.isEmpty()) {
return files;
}
// Now filter!
ListBuffer<JavaFileObject> filteredFiles = new ListBuffer<JavaFileObject>();
for (JavaFileObject f : files) {
URI uri = f.toUri();
String t = uri.toString();
if (t.startsWith("jar:")
|| t.endsWith(".class")
|| visibleSources.contains(uri))
{
filteredFiles.add(f);
}
}
return filteredFiles;
}
@Override
public JavaFileObject getJavaFileForOutput(Location location,
String className,
Kind kind,
FileObject sibling)
throws IOException
{
JavaFileObject file = super.getJavaFileForOutput(location, className, kind, sibling);
if (file == null) return file;
int dp = className.lastIndexOf('.');
String pkg_name = "";
if (dp != -1) {
pkg_name = className.substring(0, dp);
}
// When modules are in use, then the mod_name might be something like "jdk_base"
String mod_name = "";
addArtifact(mod_name+":"+pkg_name, file.toUri());
return file;
}
@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());
}
@Override
public Iterable<JavaFileObject> list(Location location,
String packageName,
Set<Kind> kinds,
boolean recurse)
throws IOException
{
// Acquire the list of files.
Iterable<JavaFileObject> files = super.list(location, packageName, kinds, recurse);
if (visibleSources.isEmpty()) {
return files;
}
// Now filter!
ListBuffer<JavaFileObject> filteredFiles = new ListBuffer<JavaFileObject>();
for (JavaFileObject f : files) {
URI uri = f.toUri();
String t = uri.toString();
if (t.startsWith("jar:")
|| t.endsWith(".class")
|| visibleSources.contains(uri))
{
filteredFiles.add(f);
}
}
return filteredFiles;
}
@Override
public Iterable<JavaFileObject> list(Location location,
String packageName, Set<Kind> kinds, boolean recurse)
throws IOException {
// validatePackageName(packageName);
nullCheck(packageName);
nullCheck(kinds);
Iterable<? extends Path> paths = getLocation(location);
if (paths == null)
return List.nil();
ListBuffer<JavaFileObject> results = new ListBuffer<JavaFileObject>();
for (Path path : paths)
list(path, packageName, kinds, recurse, results);
return results.toList();
}
@Override
public Iterable<JavaFileObject> list(Location location, String packageName, Set<Kind> kinds, boolean recurse) throws IOException {
if (location != StandardLocation.PLATFORM_CLASS_PATH || !kinds.contains(Kind.CLASS))
return Collections.emptyList();
if (!packageName.isEmpty())
packageName += ".";
List<JavaFileObject> result = new ArrayList<>();
for (Entry<String, JavaFileObject> e : className2File.entrySet()) {
String currentPackage = e.getKey().substring(0, e.getKey().lastIndexOf(".") + 1);
if (recurse ? currentPackage.startsWith(packageName) : packageName.equals(currentPackage))
result.add(e.getValue());
}
return result;
}
@Override
public Iterable<JavaFileObject> list(Location location,
String packageName, Set<Kind> kinds, boolean recurse)
throws IOException {
// validatePackageName(packageName);
nullCheck(packageName);
nullCheck(kinds);
Iterable<? extends Path> paths = getLocation(location);
if (paths == null)
return List.nil();
ListBuffer<JavaFileObject> results = new ListBuffer<JavaFileObject>();
for (Path path : paths)
list(path, packageName, kinds, recurse, results);
return results.toList();
}
public JavaFileObject toJavaFileObject() {
URI uri = URI.create((packageName.isEmpty()
? typeSpec.name
: packageName.replace('.', '/') + '/' + typeSpec.name)
+ Kind.SOURCE.extension);
return new SimpleJavaFileObject(uri, Kind.SOURCE) {
private final long lastModified = System.currentTimeMillis();
@Override public String getCharContent(boolean ignoreEncodingErrors) {
return JavaFile.this.toString();
}
@Override public InputStream openInputStream() throws IOException {
return new ByteArrayInputStream(getCharContent(true).getBytes(UTF_8));
}
@Override public long getLastModified() {
return lastModified;
}
};
}
/** Emit plain Java source for a class.
* @param env The attribution environment of the outermost class
* containing this class.
* @param cdef The class definition to be printed.
*/
JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
JavaFileObject outFile
= fileManager.getJavaFileForOutput(CLASS_OUTPUT,
cdef.sym.flatname.toString(),
JavaFileObject.Kind.SOURCE,
null);
if (inputFiles.contains(outFile)) {
log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile);
return null;
} else {
try (BufferedWriter out = new BufferedWriter(outFile.openWriter())) {
new Pretty(out, true).printUnit(env.toplevel, cdef);
if (verbose)
log.printVerbose("wrote.file", outFile);
}
return outFile;
}
}
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException {
try {
return new SimpleJavaFileObject(new URI("mem://" + className.replace('.', '/') + kind.extension), kind) {
@Override public OutputStream openOutputStream() throws IOException {
return new ByteArrayOutputStream() {
@Override public void close() throws IOException {
super.close();
name2Content.put(className, toByteArray());
}
};
}
};
} catch (URISyntaxException ex) {
throw new AssertionError(ex);
}
}
/**
* @throws IllegalArgumentException {@inheritDoc}
* @throws IllegalStateException {@inheritDoc}
*/
public JavaFileObject getJavaFileForOutput(Location location,
String className,
Kind kind,
FileObject sibling)
throws IOException
{
return fileManager.getJavaFileForOutput(location, className, kind, sibling);
}
public static Kind getKind(String name) {
if (name.endsWith(Kind.CLASS.extension))
return Kind.CLASS;
else if (name.endsWith(Kind.SOURCE.extension))
return Kind.SOURCE;
else if (name.endsWith(Kind.HTML.extension))
return Kind.HTML;
else
return Kind.OTHER;
}
@Override @DefinedBy(Api.COMPILER_TREE)
public void printMessage(Diagnostic.Kind kind, CharSequence msg,
com.sun.source.doctree.DocTree t,
com.sun.source.doctree.DocCommentTree c,
com.sun.source.tree.CompilationUnitTree root) {
printMessage(kind, msg, ((DCTree) t).pos((DCDocComment) c), root);
}
public List<CompilationMessage> addAndResolveDependencies(String[] dependencies) {
List<CompilationMessage> resolutionMessages = new ArrayList<>();
for (String dependency : dependencies) {
if (dependency.startsWith("maven:")) {
// Resolving an explicit external archive
String coordinates = dependency.replaceFirst("maven:\\/*", "");
DependencyResolver engine = DependencyResolver.instance();
try {
File resolved = engine.resolve(
new Dependency(new DefaultArtifact(coordinates), "runtime"));
// Example:
// dependency =
// maven://org.springframework:spring-expression:4.3.9.RELEASE
// resolved.toURI() =
// file:/Users/aclement/.m2/repository/
// org/springframework/spring-expression/4.3.9.RELEASE/spring-expression-4.3.9.RELEASE.jar
this.resolvedAdditionalDependencies.put(dependency, resolved);
}
catch (RuntimeException re) {
CompilationMessage compilationMessage = new CompilationMessage(
CompilationMessage.Kind.ERROR, re.getMessage(), null, 0, 0);
resolutionMessages.add(compilationMessage);
}
}
else if (dependency.startsWith("file:")) {
this.resolvedAdditionalDependencies.put(dependency,
new File(URI.create(dependency)));
}
else {
resolutionMessages.add(new CompilationMessage(
CompilationMessage.Kind.ERROR,
"Unrecognized dependency: " + dependency
+ " (expected something of the form: maven://groupId:artifactId:version)",
null, 0, 0));
}
}
return resolutionMessages;
}
@Override
public JavaFileObject getJavaFileForOutput(Location location, String qualifiedName, Kind kind, FileObject outputFile)
throws IOException {
JavaFileObject file = new JavaFileObjectImpl(qualifiedName, kind);
classLoader.add(qualifiedName, file);
return file;
}
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException {
logger.trace("Creating [email protected](location:{}, className:{}, kinds:{})", location, className, kind);
if (sibling != null && sibling instanceof DremioJavaFileObject) {
return ((DremioJavaFileObject)sibling).addOutputJavaFile(className);
}
throw new IOException("The source file passed to getJavaFileForOutput() is not a DremioJavaFileObject: " + sibling);
}
@Override
public JavaFileObject getJavaFileForInput(Location location, String className, Kind kind)
throws IOException {
if (location.isOutputLocation()) {
return inMemoryFileObjects
.getIfPresent(uriForJavaFileObject(location, className, kind));
} else {
return super.getJavaFileForInput(location, className, kind);
}
}
/** Implement policy to choose to derive information from a source
* file or a class file when both are present. May be overridden
* by subclasses.
*/
protected JavaFileObject preferredFileObject(JavaFileObject a,
JavaFileObject b) {
if (preferSource)
return (a.getKind() == JavaFileObject.Kind.SOURCE) ? a : b;
else {
long adate = a.getLastModified();
long bdate = b.getLastModified();
// 6449326: policy for bad lastModifiedTime in ClassReader
//assert adate >= 0 && bdate >= 0;
return (adate > bdate) ? a : b;
}
}
/**
* Constructs a memory file object.
* @param name binary name of the class to be stored in this file object
*/
MemoryFileObject(Location location, String name, JavaFileObject.Kind kind) {
super(URI.create("mfm:///" + name.replace('.','/') + kind.extension),
Kind.CLASS);
this.location = location;
this.name = name;
}
/**
* @throws IllegalArgumentException {@inheritDoc}
* @throws UnsupportedOperationException {@inheritDoc}
* @throws IllegalStateException {@inheritDoc}
*/
@DefinedBy(Api.COMPILER)
public JavaFileObject getJavaFileForOutput(Location location,
String className,
Kind kind,
FileObject sibling)
throws IOException
{
return wrap(super.getJavaFileForOutput(location, className, kind, unwrap(sibling)));
}
/**
* Construct a SimpleJavaFileObject of the given kind and with the
* given URI.
*
* @param uri the URI for this file object
* @param kind the kind of this file object
*/
protected SimpleJavaFileObject(URI uri, Kind kind) {
Objects.requireNonNull(uri);
Objects.requireNonNull(kind);
if (uri.getPath() == null)
throw new IllegalArgumentException("URI must have a path: " + uri);
this.uri = uri;
this.kind = kind;
}
private static void verifyLambdaScopeCorrect(final String packageClause) throws Exception {
JavacTool tool = JavacTool.create();
JavaFileObject source = new SimpleJavaFileObject(URI.create("mem://Test.java"), Kind.SOURCE) {
@Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
return packageClause + SOURCE_CODE;
}
@Override public boolean isNameCompatible(String simpleName, Kind kind) {
return true;
}
};
Iterable<? extends JavaFileObject> fos = Collections.singletonList(source);
JavacTask task = tool.getTask(null, null, null, new ArrayList<String>(), null, fos);
final Types types = JavacTypes.instance(((JavacTaskImpl) task).getContext());
final Trees trees = Trees.instance(task);
CompilationUnitTree cu = task.parse().iterator().next();
task.analyze();
new TreePathScanner<Void, Void>() {
@Override public Void visitMemberSelect(MemberSelectTree node, Void p) {
if (node.getIdentifier().contentEquals("correct")) {
TypeMirror xType = trees.getTypeMirror(new TreePath(getCurrentPath(), node.getExpression()));
Scope scope = trees.getScope(getCurrentPath());
for (Element l : scope.getLocalElements()) {
if (!l.getSimpleName().contentEquals("x")) continue;
if (!types.isSameType(xType, l.asType())) {
throw new IllegalStateException("Incorrect variable type in scope: " + l.asType() + "; should be: " + xType);
}
}
}
return super.visitMemberSelect(node, p);
}
}.scan(cu, null);
}
@Override
public JavaFileObject getJavaFileForOutput(Location location, String qualifiedName, Kind kind, FileObject outputFile)
throws IOException {
JavaFileObject file = new JavaFileObjectImpl(qualifiedName, kind);
classLoader.add(qualifiedName, file);
return file;
}
/**
* @throws IllegalStateException {@inheritDoc}
*/
public Iterable<JavaFileObject> list(Location location,
String packageName,
Set<Kind> kinds,
boolean recurse)
throws IOException
{
return wrap(super.list(location, packageName, kinds, recurse));
}
/**
* @throws IllegalStateException {@inheritDoc}
*/
public Iterable<JavaFileObject> list(Location location,
String packageName,
Set<Kind> kinds,
boolean recurse)
throws IOException
{
return wrap(super.list(location, packageName, kinds, recurse));
}
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className,
Kind kind, FileObject sibling)
throws IOException {
if (!file.getClassName().equals(className)) {
throw new IOException("Expected class with name " + file.getClassName() +
", but got " + className);
}
return file;
}
public Key(Location location, String classpath, String packageName, Set<Kind> kinds, boolean recurse) {
this.location = location;
this.classpath = classpath;
this.packageName = packageName;
this.kinds = kinds;
this.recurse = recurse;
}