本文整理汇总了Java中com.sun.source.util.Trees类的典型用法代码示例。如果您正苦于以下问题:Java Trees类的具体用法?Java Trees怎么用?Java Trees使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Trees类属于com.sun.source.util包,在下文中一共展示了Trees类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: init
import com.sun.source.util.Trees; //导入依赖的package包/类
@Override public synchronized void init(ProcessingEnvironment env) {
super.init(env);
String sdk = env.getOptions().get(OPTION_SDK_INT);
if (sdk != null) {
try {
this.sdk = Integer.parseInt(sdk);
} catch (NumberFormatException e) {
env.getMessager()
.printMessage(Kind.WARNING, "Unable to parse supplied minSdk option '"
+ sdk
+ "'. Falling back to API 1 support.");
}
}
elementUtils = env.getElementUtils();
typeUtils = env.getTypeUtils();
filer = env.getFiler();
try {
trees = Trees.instance(processingEnv);
} catch (IllegalArgumentException ignored) {
}
}
示例2: findTopClassElems
import com.sun.source.util.Trees; //导入依赖的package包/类
/**
*
* @return list of {@code Element}s representing top classes,
* or an empty list of none were found
*/
private static List<TypeElement> findTopClassElems(
CompilationInfo compInfo,
CompilationUnitTree compilationUnit,
Filter filter) {
List<? extends Tree> typeDecls = compilationUnit.getTypeDecls();
if ((typeDecls == null) || typeDecls.isEmpty()) {
return Collections.<TypeElement>emptyList();
}
List<TypeElement> result = new ArrayList<TypeElement>(typeDecls.size());
Trees trees = compInfo.getTrees();
for (Tree typeDecl : typeDecls) {
if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDecl.getKind())) {
Element element = trees.getElement(
new TreePath(new TreePath(compilationUnit), typeDecl));
TypeElement typeElement = (TypeElement) element;
if (filter.passes(typeElement, compInfo)) {
result.add(typeElement);
}
}
}
return result;
}
示例3: process
import com.sun.source.util.Trees; //导入依赖的package包/类
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
new TestPathScanner<Void>() {
@Override
public void visit(Void t) {
}
};
TypeElement currentClass = elements.getTypeElement("TypesCachesCleared");
Trees trees = Trees.instance(processingEnv);
TreePath path = trees.getPath(currentClass);
new TreePathScanner<Void, Void>() {
@Override public Void visitClass(ClassTree node, Void p) {
trees.getElement(getCurrentPath());
return super.visitClass(node, p);
}
}.scan(path, null);
return false;
}
示例4: visitCompilationUnit
import com.sun.source.util.Trees; //导入依赖的package包/类
@Override
public Tree visitCompilationUnit(CompilationUnitTree node, Element p) {
this.referencedPrivateElement = new HashSet<Element>();
Tree result = super.visitCompilationUnit(node, p);
for (Element privEl : this.referencedPrivateElement) {
problem = MoveTransformer.createProblem(problem, false, NbBundle.getMessage(InnerToOuterRefactoringPlugin.class, "WRN_InnerToOuterRefToPrivate", privEl));
}
Trees trees = workingCopy.getTrees();
CompilationUnitTree newNode = node;
for (ImportTree imp : node.getImports()) {
if(imp.isStatic()) {
Tree qualIdent = imp.getQualifiedIdentifier();
TypeElement el = workingCopy.getElements().getTypeElement(qualIdent.toString());
if(inner.equals(el)) {
newNode = make.removeCompUnitImport(newNode, imp);
}
}
}
if(newNode != node) {
rewrite(node, newNode);
}
return result;
}
示例5: visitNewClass
import com.sun.source.util.Trees; //导入依赖的package包/类
@Override
public Tree visitNewClass(NewClassTree node, Element p) {
if(isCancelled.get()) {
return null;
}
Trees trees = workingCopy.getTrees();
ClassTree classTree = ((NewClassTree) node).getClassBody();
if (classTree != null && p.getKind() == ElementKind.CONSTRUCTOR) {
Element anonClass = workingCopy.getTrees().getElement(TreePath.getPath(workingCopy.getCompilationUnit(), classTree));
if (anonClass == null) {
Logger.getLogger("org.netbeans.modules.refactoring.java").log(Level.SEVERE, "FindUsages cannot resolve {0}", classTree); // NOI18N
} else {
for (ExecutableElement c : ElementFilter.constructorsIn(anonClass.getEnclosedElements())) {
MethodTree t = workingCopy.getTrees().getTree(c);
TreePath superCall = trees.getPath(workingCopy.getCompilationUnit(), ((ExpressionStatementTree) t.getBody().getStatements().get(0)).getExpression());
Element superCallElement = trees.getElement(superCall);
if (superCallElement != null && superCallElement.equals(p) && !workingCopy.getTreeUtilities().isSynthetic(superCall)) {
addUsage(superCall);
}
}
}
} else {
addIfMatch(getCurrentPath(), node, p);
}
return super.visitNewClass(node, p);
}
示例6: visitClass
import com.sun.source.util.Trees; //导入依赖的package包/类
@Override
public Tree visitClass(ClassTree node, Element elementToFind) {
if (workingCopy.getTreeUtilities().isSynthetic(getCurrentPath())) {
return super.visitClass(node, elementToFind);
}
Trees trees = workingCopy.getTrees();
Types types = workingCopy.getTypes();
TypeMirror type2 = elementToFind.asType();
type2 = types.erasure(type2);
if (recursive) {
TypeMirror type1 = trees.getTypeMirror(getCurrentPath());
if (type1 != null) {
type1 = types.erasure(type1);
if (isSubtype(type1, type2)) {
addUsage(getCurrentPath());
}
}
} else {
TypeElement el = (TypeElement) workingCopy.getTrees().getElement(getCurrentPath());
if (el != null && el.getSuperclass()!=null && types.isSameType(types.erasure(el.getSuperclass()), type2) || containsType(el.getInterfaces(), type2)) {
addUsage(getCurrentPath());
}
}
return super.visitClass(node, elementToFind);
}
示例7: visitVariable
import com.sun.source.util.Trees; //导入依赖的package包/类
@Override
public Tree visitVariable(VariableTree variableDeclTree, Trees trees) {
//check for shadowed variable
if (isNameAlreadyUsed(variableDeclTree.getName())) {
TreePath path = getCurrentPath();
CharSequence newName = getUniqueName(variableDeclTree.getName());
Element el = trees.getElement(path);
if (el != null) {
originalToNewName.put(el, newName);
}
VariableTree newTree = copy.getTreeMaker()
.Variable(variableDeclTree.getModifiers(), newName, variableDeclTree.getType(), variableDeclTree.getInitializer());
copy.rewrite(variableDeclTree, newTree);
}
return super.visitVariable(variableDeclTree, trees);
}
示例8: addGuaranteedNonNullFromInvokes
import com.sun.source.util.Trees; //导入依赖的package包/类
private void addGuaranteedNonNullFromInvokes(
VisitorState state,
Trees trees,
Set<Element> safeInitMethods,
AccessPathNullnessAnalysis nullnessAnalysis,
Set<Element> guaranteedNonNull) {
for (Element invoked : safeInitMethods) {
Tree invokedTree = trees.getTree(invoked);
guaranteedNonNull.addAll(
nullnessAnalysis.getNonnullFieldsOfReceiverAtExit(
new TreePath(state.getPath(), invokedTree), state.context));
}
}
示例9: findResourceUsages
import com.sun.source.util.Trees; //导入依赖的package包/类
private static Collection<? extends TreePath> findResourceUsages(
final VariableElement resource,
final Collection<? extends TreePath> statements,
final Trees trees) {
final List<TreePath> usages = new LinkedList<>();
if (statements != null) {
final ErrorAwareTreePathScanner<List<TreePath>,List<TreePath>> scanner = new ErrorAwareTreePathScanner<List<TreePath>, List<TreePath>>() {
@Override
public List<TreePath> visitIdentifier(IdentifierTree node, List<TreePath> p) {
final TreePath path = getCurrentPath();
final Element element = trees.getElement(path);
if (element == resource) {
usages.add(path);
}
return super.visitIdentifier(node, p);
}
};
for (TreePath st : statements) {
scanner.scan(st, usages);
}
}
return usages;
}
示例10: testPositionForEnumModifiers
import com.sun.source.util.Trees; //导入依赖的package包/类
@Test
void testPositionForEnumModifiers() throws IOException {
final String theString = "public";
String code = "package test; " + theString + " enum Test {A;}";
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null, null,
null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();
SourcePositions pos = Trees.instance(ct).getSourcePositions();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
ModifiersTree mt = clazz.getModifiers();
int spos = code.indexOf(theString);
int epos = spos + theString.length();
assertEquals("testPositionForEnumModifiers",
spos, pos.getStartPosition(cut, mt));
assertEquals("testPositionForEnumModifiers",
epos, pos.getEndPosition(cut, mt));
}
示例11: createDefaultMethodBody
import com.sun.source.util.Trees; //导入依赖的package包/类
private static BlockTree createDefaultMethodBody(WorkingCopy wc, TreePath targetTree, TypeMirror returnType, String name) {
TreeUtilities tu = wc.getTreeUtilities();
TypeElement targetClazz = (TypeElement)wc.getTrees().getElement(targetTree);
StatementTree st = tu.parseStatement("{class ${abstract " + (returnType != null ? returnType.toString() : "void") + " " + ("<init>".equals(name) ? targetClazz.getSimpleName() : name) + "();}}", new SourcePositions[1]); //NOI18N
Trees trees = wc.getTrees();
List<? extends Tree> members = ((ClassTree) targetTree.getLeaf()).getMembers();
Scope scope = members.isEmpty() ? trees.getScope(targetTree) : trees.getScope(new TreePath(targetTree, members.get(0)));
tu.attributeTree(st, scope);
Tree first = null;
for(Tree t : ((ClassTree)((BlockTree)st).getStatements().get(0)).getMembers()) {
if (t.getKind() == Tree.Kind.METHOD && !"<init>".contentEquals(((MethodTree)t).getName())) { //NOI19N
first = t;
break;
}
}
ExecutableElement ee = (ExecutableElement) wc.getTrees().getElement(new TreePath(targetTree, first));
return GeneratorUtilities.get(wc).createAbstractMethodImplementation(targetClazz, ee).getBody();
}
示例12: main
import com.sun.source.util.Trees; //导入依赖的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);
}
示例13: assignmentToCatchBlockParameter
import com.sun.source.util.Trees; //导入依赖的package包/类
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.AssignmentIssues.assignmentToCatchBlockParameter", description = "#DESC_org.netbeans.modules.java.hints.AssignmentIssues.assignmentToCatchBlockParameter", category = "assignment_issues", enabled = false, suppressWarnings = "AssignmentToCatchBlockParameter", options=Options.QUERY) //NOI18N
@TriggerTreeKind(Kind.CATCH)
public static List<ErrorDescription> assignmentToCatchBlockParameter(HintContext context) {
final Trees trees = context.getInfo().getTrees();
final TreePath catchPath = context.getPath();
final Element param = trees.getElement(TreePath.getPath(catchPath, ((CatchTree) catchPath.getLeaf()).getParameter()));
if (param == null || param.getKind() != ElementKind.EXCEPTION_PARAMETER) {
return null;
}
final TreePath block = TreePath.getPath(catchPath, ((CatchTree) catchPath.getLeaf()).getBlock());
final List<TreePath> paths = new LinkedList<TreePath>();
new AssignmentFinder(trees, param).scan(block, paths);
final List<ErrorDescription> ret = new ArrayList<ErrorDescription>(paths.size());
for (TreePath path : paths) {
ret.add(ErrorDescriptionFactory.forTree(context, path, NbBundle.getMessage(AssignmentIssues.class, "MSG_AssignmentToCatchBlockParameter", param.getSimpleName()))); //NOI18N
}
return ret;
}
示例14: FindPosScanner
import com.sun.source.util.Trees; //导入依赖的package包/类
FindPosScanner(
@NonNull final FileObject target,
@NonNull final Trees trees,
@NonNull final Elements elements,
@NonNull final TreeUtilities treeUtilities,
@NonNull final Collection<? extends ProfileSupport.Violation> violations,
@NonNull final Result errors) {
assert target != null;
assert trees != null;
assert elements != null;
assert treeUtilities != null;
assert violations != null;
assert errors != null;
this.target = target;
this.trees = trees;
this.elements = elements;
this.treeUtilities = treeUtilities;
this.errors = errors;
for (ProfileSupport.Violation v : violations) {
final ElementHandle<TypeElement> eh = v.getUsedType();
if (eh != null) {
violationsByBinNames.put(eh.getBinaryName(), v);
}
}
}
示例15: run
import com.sun.source.util.Trees; //导入依赖的package包/类
void run() throws Exception {
Context context = new Context();
JavacFileManager.preRegister(context);
Trees trees = JavacTrees.instance(context);
StringWriter strOut = new StringWriter();
PrintWriter pw = new PrintWriter(strOut);
DPrinter dprinter = new DPrinter(pw, trees);
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, Arrays.asList(new JavaSource()));
Iterable<? extends CompilationUnitTree> elements = ct.parse();
ct.analyze();
Assert.check(elements.iterator().hasNext());
dprinter.treeTypes(true).printTree("", (JCTree)elements.iterator().next());
String output = strOut.toString();
Assert.check(!output.contains("java.lang.Object"), "there shouldn't be any type instantiated to Object");
}