下面列出了com.sun.source.tree.ModifiersTree#getAnnotations ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override public Description matchClass(ClassTree tree, VisitorState state) {
if (tree.getKind() != CLASS) {
return NO_MATCH;
}
ModifiersTree modifiers = tree.getModifiers();
Set<Modifier> modifierFlags = modifiers.getFlags();
if (modifierFlags.contains(FINAL) || modifierFlags.contains(ABSTRACT)) {
return NO_MATCH;
}
switch (ASTHelpers.getSymbol(tree).getNestingKind()) {
case LOCAL:
case ANONYMOUS:
return NO_MATCH;
case MEMBER:
if (modifierFlags.contains(PRIVATE)) {
return NO_MATCH;
}
break;
case TOP_LEVEL:
break;
}
for (AnnotationTree annotation : modifiers.getAnnotations()) {
AnnotationMirror annotationMirror = ASTHelpers.getAnnotationMirror(annotation);
if (annotationMirror.getAnnotationType().toString().equals(OPEN_FQCN)) {
return NO_MATCH;
}
}
return describeMatch(tree);
}
/**
* Can a local with a set of modifiers be declared with horizontal annotations? This is currently
* true if there is at most one marker annotation, and no others.
*
* @param modifiers the list of {@link ModifiersTree}s
* @return whether the local can be declared with horizontal annotations
*/
private Direction canLocalHaveHorizontalAnnotations(ModifiersTree modifiers) {
int markerAnnotations = 0;
for (AnnotationTree annotation : modifiers.getAnnotations()) {
if (annotation.getArguments().isEmpty()) {
markerAnnotations++;
}
}
return markerAnnotations <= 1 && markerAnnotations == modifiers.getAnnotations().size()
? Direction.HORIZONTAL
: Direction.VERTICAL;
}
/**
* Should a field with a set of modifiers be declared with horizontal annotations? This is
* currently true if all annotations are marker annotations.
*/
private Direction fieldAnnotationDirection(ModifiersTree modifiers) {
for (AnnotationTree annotation : modifiers.getAnnotations()) {
if (!annotation.getArguments().isEmpty()) {
return Direction.VERTICAL;
}
}
return Direction.HORIZONTAL;
}
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
ModifiersTree mt = (ModifiersTree) ctx.getPath().getLeaf();
for (AnnotationTree at : mt.getAnnotations()) {
Element el = ctx.getWorkingCopy().getTrees().getElement(new TreePath(ctx.getPath(), at));
if (el != null && el.getKind().isInterface() && ((TypeElement ) el).getQualifiedName().contentEquals("java.lang.Override")) {
ctx.getWorkingCopy().rewrite(mt, ctx.getWorkingCopy().getTreeMaker().removeModifiersAnnotation(mt, at));
return ;
}
}
}
public void fixTimerAnnotation(WorkingCopy copy) {
TypeElement scheduleAnnotation = copy.getElements().getTypeElement(EJBAPIAnnotations.SCHEDULE);
ModifiersTree modifiers = ((MethodTree) copy.getTrees().getPath(methodElement.resolve(copy)).getLeaf()).getModifiers();
TreeMaker tm = copy.getTreeMaker();
for (AnnotationTree at : modifiers.getAnnotations()) {
TreePath tp = new TreePath(new TreePath(copy.getCompilationUnit()), at.getAnnotationType());
Element e = copy.getTrees().getElement(tp);
if (scheduleAnnotation.equals(e)) {
List<? extends ExpressionTree> arguments = at.getArguments();
for (ExpressionTree et : arguments) {
if (et.getKind() == Tree.Kind.ASSIGNMENT) {
AssignmentTree assignment = (AssignmentTree) et;
AssignmentTree newAssignment = tm.Assignment(assignment.getVariable(), tm.Literal(false));
if (EJBAPIAnnotations.PERSISTENT.equals(assignment.getVariable().toString())) {
copy.rewrite(
modifiers,
copy.getTreeUtilities().translate(modifiers, Collections.singletonMap(et, newAssignment)));
return;
}
}
}
List<ExpressionTree> newArguments = new ArrayList<ExpressionTree>(arguments);
ExpressionTree persistenQualIdent = tm.QualIdent(EJBAPIAnnotations.PERSISTENT);
newArguments.add(tm.Assignment(persistenQualIdent, tm.Literal(false)));
AnnotationTree newAnnotation = tm.Annotation(tp.getLeaf(), newArguments);
copy.rewrite(at, newAnnotation);
return;
}
}
}
private AnnotationTree findFxmlAnnotation(ModifiersTree modTree) {
for (AnnotationTree annTree : modTree.getAnnotations()) {
TreePath tp = new TreePath(new TreePath(wcopy.getCompilationUnit()), annTree.getAnnotationType());
Element e = wcopy.getTrees().getElement(tp);
if (fxmlAnnotationType.equals(e)) {
return annTree;
}
}
return null;
}
/**
* Can a local with a set of modifiers be declared with horizontal annotations? This is currently
* true if there is at most one marker annotation, and no others.
*
* @param modifiers the list of {@link ModifiersTree}s
* @return whether the local can be declared with horizontal annotations
*/
private Direction canLocalHaveHorizontalAnnotations(ModifiersTree modifiers) {
int markerAnnotations = 0;
for (AnnotationTree annotation : modifiers.getAnnotations()) {
if (annotation.getArguments().isEmpty()) {
markerAnnotations++;
}
}
return markerAnnotations <= 1 && markerAnnotations == modifiers.getAnnotations().size()
? Direction.HORIZONTAL
: Direction.VERTICAL;
}
/**
* Should a field with a set of modifiers be declared with horizontal annotations? This is
* currently true if all annotations are marker annotations.
*/
private Direction fieldAnnotationDirection(ModifiersTree modifiers) {
for (AnnotationTree annotation : modifiers.getAnnotations()) {
if (!annotation.getArguments().isEmpty()) {
return Direction.VERTICAL;
}
}
return Direction.HORIZONTAL;
}
/**
* Can a local with a set of modifiers be declared with horizontal annotations? This is currently
* true if there is at most one parameterless annotation, and no others.
*
* @param modifiers the list of {@link ModifiersTree}s
* @return whether the local can be declared with horizontal annotations
*/
private Direction canLocalHaveHorizontalAnnotations(ModifiersTree modifiers) {
int parameterlessAnnotations = 0;
for (AnnotationTree annotation : modifiers.getAnnotations()) {
if (annotation.getArguments().isEmpty()) {
parameterlessAnnotations++;
}
}
return parameterlessAnnotations <= 1
&& parameterlessAnnotations == modifiers.getAnnotations().size()
? Direction.HORIZONTAL
: Direction.VERTICAL;
}
/**
* Should a field with a set of modifiers be declared with horizontal annotations? This is
* currently true if all annotations are parameterless annotations.
*/
private Direction fieldAnnotationDirection(ModifiersTree modifiers) {
for (AnnotationTree annotation : modifiers.getAnnotations()) {
if (!annotation.getArguments().isEmpty()) {
return Direction.VERTICAL;
}
}
return Direction.HORIZONTAL;
}
private List<Annotation> convertAnnotations(ModifiersTree modifiers, TreePath parent) {
List<Annotation> annotations = new ArrayList<>();
TreePath path = getTreePath(parent, modifiers);
for (AnnotationTree annotation : modifiers.getAnnotations()) {
annotations.add((Annotation) convert(annotation, path));
}
return annotations;
}
public ChangeInfo implement(){
CancellableTask<WorkingCopy> task = new CancellableTask<WorkingCopy>(){
public void cancel() {}
public void run(WorkingCopy workingCopy) throws Exception {
workingCopy.toPhase(JavaSource.Phase.RESOLVED);
TypeElement clazz = classHandle.resolve(workingCopy);
if (clazz != null){
for (ExecutableElement methodElem : ElementFilter.methodsIn(clazz.getEnclosedElements())){
if (methodElem.getSimpleName().toString().startsWith("get")){ //NOI18N
VariableElement fieldElem = ModelUtils.getField(clazz, ModelUtils.getFieldNameFromAccessor(methodElem.getSimpleName().toString()));
if (fieldElem != null){
MethodTree methodTree = workingCopy.getTrees().getTree((methodElem));
VariableTree fieldTree = (VariableTree) workingCopy.getTrees().getTree(fieldElem);
ModifiersTree srcModifiersTree = getSourceModifiers(fieldTree, methodTree);
List <AnnotationTree> remainingAnnotations = new LinkedList<AnnotationTree>();
List <AnnotationTree> newTargetAnnots = new LinkedList<AnnotationTree>();
for (AnnotationTree annTree : srcModifiersTree.getAnnotations()){
if (isJPAAttrAnnotation(workingCopy, annTree)){
newTargetAnnots.add(annTree);
} else {
remainingAnnotations.add(annTree);
}
}
if (newTargetAnnots.size() > 0){
TreeMaker make = workingCopy.getTreeMaker();
ModifiersTree targetModifiers = getTargetModifiers(fieldTree, methodTree);
workingCopy.rewrite(srcModifiersTree, make.Modifiers(srcModifiersTree, remainingAnnotations));
newTargetAnnots.addAll(targetModifiers.getAnnotations());
workingCopy.rewrite(targetModifiers,make.Modifiers(targetModifiers,newTargetAnnots));
}
}
}
}
}
}
};
JavaSource javaSource = JavaSource.forFileObject(fileObject);
try{
javaSource.runModificationTask(task).commit();
} catch (IOException e){
JPAProblemFinder.LOG.log(Level.SEVERE, e.getMessage(), e);
}
return null;
}
private static boolean isAlreadyRegistered(TreePath treePath, String key) {
ModifiersTree modifiers;
Tree tree = treePath.getLeaf();
switch (tree.getKind()) {
case METHOD:
modifiers = ((MethodTree) tree).getModifiers();
break;
case VARIABLE:
modifiers = ((VariableTree) tree).getModifiers();
break;
case CLASS:
case ENUM:
case INTERFACE:
case ANNOTATION_TYPE:
modifiers = ((ClassTree) tree).getModifiers();
break;
default:
modifiers = null;
}
if (modifiers != null) {
for (AnnotationTree ann : modifiers.getAnnotations()) {
Tree annotationType = ann.getAnnotationType();
if (annotationType.toString().matches("((org[.]openide[.]util[.])?NbBundle[.])?Messages")) { // XXX see above
List<? extends ExpressionTree> args = ann.getArguments();
if (args.size() != 1) {
continue; // ?
}
AssignmentTree assign = (AssignmentTree) args.get(0);
if (!assign.getVariable().toString().equals("value")) {
continue; // ?
}
ExpressionTree arg = assign.getExpression();
if (arg.getKind() == Tree.Kind.STRING_LITERAL) {
if (isRegistered(key, arg)) {
return true;
}
} else if (arg.getKind() == Tree.Kind.NEW_ARRAY) {
for (ExpressionTree elt : ((NewArrayTree) arg).getInitializers()) {
if (isRegistered(key, elt)) {
return true;
}
}
} else {
// ?
}
}
}
}
TreePath parentPath = treePath.getParentPath();
if (parentPath == null) {
return false;
}
// XXX better to check all sources in the same package
return isAlreadyRegistered(parentPath, key);
}
Description.Builder addSuppressWarningsFix(
Tree suggestTree, Description.Builder builder, String suppressionName) {
SuppressWarnings extantSuppressWarnings = null;
Symbol treeSymbol = ASTHelpers.getSymbol(suggestTree);
if (treeSymbol != null) {
extantSuppressWarnings = treeSymbol.getAnnotation(SuppressWarnings.class);
}
SuggestedFix fix;
if (extantSuppressWarnings == null) {
fix =
SuggestedFix.prefixWith(
suggestTree,
"@SuppressWarnings(\""
+ suppressionName
+ "\") "
+ config.getAutofixSuppressionComment());
} else {
// need to update the existing list of warnings
final List<String> suppressions = Lists.newArrayList(extantSuppressWarnings.value());
suppressions.add(suppressionName);
// find the existing annotation, so we can replace it
final ModifiersTree modifiers =
(suggestTree instanceof MethodTree)
? ((MethodTree) suggestTree).getModifiers()
: ((VariableTree) suggestTree).getModifiers();
final List<? extends AnnotationTree> annotations = modifiers.getAnnotations();
// noinspection ConstantConditions
com.google.common.base.Optional<? extends AnnotationTree> suppressWarningsAnnot =
Iterables.tryFind(
annotations,
annot -> annot.getAnnotationType().toString().endsWith("SuppressWarnings"));
if (!suppressWarningsAnnot.isPresent()) {
throw new AssertionError("something went horribly wrong");
}
final String replacement =
"@SuppressWarnings({"
+ Joiner.on(',').join(Iterables.transform(suppressions, s -> '"' + s + '"'))
+ "}) "
+ config.getAutofixSuppressionComment();
fix = SuggestedFix.replace(suppressWarningsAnnot.get(), replacement);
}
return builder.addFix(fix);
}