/** * Creates annotation * <code>@org.junit.runners.Suite.SuiteClasses({...})</code>. * * @param suiteMembers fully qualified names of classes to be included * in the test suite * @param created annotation */ private AnnotationTree createSuiteAnnotation(List<String> suiteMembers, WorkingCopy workingCopy) { final TreeMaker maker = workingCopy.getTreeMaker(); List<ExpressionTree> suiteMemberExpressions = new ArrayList<ExpressionTree>(suiteMembers.size()); for (String suiteMember : suiteMembers) { suiteMemberExpressions.add( maker.MemberSelect( getClassIdentifierTree(suiteMember, workingCopy), "class")); //NOI18N } /* @Suite.SuiteClasses({TestA.class, TestB.class, ...}) */ return maker.Annotation( maker.MemberSelect( getClassIdentifierTree(ANN_SUITE, workingCopy), ANN_SUITE_MEMBERS), Collections.singletonList( maker.NewArray( null, //do not generate "new Class[]" Collections.<ExpressionTree>emptyList(), suiteMemberExpressions))); }
public static ExpressionTree findValue(AnnotationTree m, String name) { for (ExpressionTree et : m.getArguments()) { if (et.getKind() == Kind.ASSIGNMENT) { AssignmentTree at = (AssignmentTree) et; String varName = ((IdentifierTree) at.getVariable()).getName().toString(); if (varName.equals(name)) { return at.getExpression(); } } if (et instanceof LiteralTree/*XXX*/ && "value".equals(name)) { return et; } } return null; }
public static List<AnnotationTree> findArrayValue(AnnotationTree at, String name) { ExpressionTree fixesArray = findValue(at, name); List<AnnotationTree> fixes = new LinkedList<AnnotationTree>(); if (fixesArray != null && fixesArray.getKind() == Kind.NEW_ARRAY) { NewArrayTree trees = (NewArrayTree) fixesArray; for (ExpressionTree fix : trees.getInitializers()) { if (fix.getKind() == Kind.ANNOTATION) { fixes.add((AnnotationTree) fix); } } } if (fixesArray != null && fixesArray.getKind() == Kind.ANNOTATION) { fixes.add((AnnotationTree) fixesArray); } return fixes; }
private void cleanMethod(MethodTree mt) { AnnotationTree t = findFxmlAnnotation(mt.getModifiers()); if (t == null) { return; } if (!isUsed(mt, mt.getModifiers())) { // must have empty body, I don't want to destroy user code: if (mt.getBody().getStatements().isEmpty()) { controllerClass = wcopy.getTreeMaker().removeClassMember(controllerClass, mt); return; } } wcopy.rewrite( mt.getModifiers(), wcopy.getTreeMaker().removeModifiersAnnotation(mt.getModifiers(), t) ); }
/** * Accumulates a flattened list of array dimensions specifiers with type annotations, and returns * the base type. * <p> * <p>Given {@code int @A @B [][] @C []}, adds {@code [[@A, @B], [@C]]} to dims and returns {@code * int}. */ private static Tree extractDims(Deque<List<AnnotationTree>> dims, Tree node) { switch (node.getKind()) { case ARRAY_TYPE: return extractDims(dims, ((ArrayTypeTree) node).getType()); // TODO: 22-Jul-17 missing type /* case ANNOTATED_TYPE: AnnotatedTypeTree annotatedTypeTree = (AnnotatedTypeTree) node; if (annotatedTypeTree.getUnderlyingType().getKind() != Tree.Kind.ARRAY_TYPE) { return node; } node = extractDims(dims, annotatedTypeTree.getUnderlyingType()); dims.addFirst(ImmutableList.<AnnotationTree>copyOf(annotatedTypeTree.getAnnotations())); return node;*/ default: return node; } }
/** * Adds an annotation to a method. This is equivalent to {@link TreeMaker#addModifiersAnnotation}, * but it creates and returns a new <code>MethodTree, not a new <code>ModifiersTree</code>. * * @param methodTree the method to add the annotation to; cannot be null. * @param annotationTree the annotation to add; cannot be null. * @return a new method annotated with the new annotation; never null. */ public MethodTree addAnnotation(MethodTree methodTree, AnnotationTree annotationTree) { Parameters.notNull("methodTree", methodTree); // NOI18N Parameters.notNull("annotationTree", annotationTree); // NOI18N TreeMaker make = getTreeMaker(); return make.Method( make.addModifiersAnnotation(methodTree.getModifiers(), annotationTree), methodTree.getName(), methodTree.getReturnType(), methodTree.getTypeParameters(), methodTree.getParameters(), methodTree.getThrows(), methodTree.getBody(), (ExpressionTree)methodTree.getDefaultValue()); }
private ModifiersTree computeMods(Element e) { Set<Modifier> implicitModifiers = IMPLICIT_MODIFIERS.get(Arrays.asList(e.getKind())); if (implicitModifiers == null) { implicitModifiers = IMPLICIT_MODIFIERS.get(Arrays.asList(e.getKind(), e.getEnclosingElement().getKind())); } Set<Modifier> modifiers = EnumSet.noneOf(Modifier.class); modifiers.addAll(e.getModifiers()); if (implicitModifiers != null) { modifiers.removeAll(implicitModifiers); } List<AnnotationTree> annotations = new LinkedList<AnnotationTree>(); for (AnnotationMirror m : e.getAnnotationMirrors()) { annotations.add(computeAnnotationTree(m)); } return make.Modifiers(modifiers, annotations); }
private AnnotationTree computeAnnotationTree(AnnotationMirror am) { List<ExpressionTree> params = new LinkedList<ExpressionTree>(); for (Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : am.getElementValues().entrySet()) { ExpressionTree val = createTreeForAnnotationValue(make, entry.getValue()); if (val == null) { LOG.log(Level.WARNING, "Cannot create annotation for: {0}", entry.getValue()); continue; } ExpressionTree vt = make.Assignment(make.Identifier(entry.getKey().getSimpleName()), val); params.add(vt); } return make.Annotation(make.Type(am.getAnnotationType()), params); }
private void visitEnumConstantDeclaration(VariableTree enumConstant) { for (AnnotationTree annotation : enumConstant.getModifiers().getAnnotations()) { scan(annotation, null); builder.forcedBreak(); } visit(enumConstant.getName()); NewClassTree init = ((NewClassTree) enumConstant.getInitializer()); if (init.getArguments().isEmpty()) { builder.guessToken("("); builder.guessToken(")"); } else { addArguments(init.getArguments(), plusFour); } if (init.getClassBody() != null) { addBodyDeclarations( init.getClassBody().getMembers(), BracesOrNot.YES, FirstDeclarationsOrNot.YES); } }
void visitVariables( List<VariableTree> fragments, DeclarationKind declarationKind, Direction annotationDirection) { if (fragments.size() == 1) { VariableTree fragment = fragments.get(0); declareOne( declarationKind, annotationDirection, Optional.of(fragment.getModifiers()), fragment.getType(), VarArgsOrNot.fromVariable(fragment), ImmutableList.<AnnotationTree>of(), fragment.getName(), "", "=", Optional.fromNullable(fragment.getInitializer()), Optional.of(";"), Optional.<ExpressionTree>absent(), Optional.fromNullable(variableFragmentDims(true, 0, fragment.getType()))); } else { declareMany(fragments, annotationDirection); } }
private void visitPackage( ExpressionTree packageName, List<? extends AnnotationTree> packageAnnotations) { if (!packageAnnotations.isEmpty()) { for (AnnotationTree annotation : packageAnnotations) { builder.forcedBreak(); scan(annotation, null); } builder.forcedBreak(); } builder.open(plusFour); token("package"); builder.space(); visitName(packageName); builder.close(); token(";"); }
boolean visitSingleMemberAnnotation(AnnotationTree node) { if (node.getArguments().size() != 1) { return false; } ExpressionTree value = Iterables.getOnlyElement(node.getArguments()); if (value.getKind() == ASSIGNMENT) { return false; } boolean isArrayInitializer = value.getKind() == NEW_ARRAY; builder.open(isArrayInitializer ? ZERO : plusFour); token("@"); scan(node.getAnnotationType(), null); token("("); if (!isArrayInitializer) { builder.breakOp(); } scan(value, null); builder.close(); token(")"); return true; }
/** * Helper method for annotations. */ private void visitAnnotations( List<? extends AnnotationTree> annotations, BreakOrNot breakBefore, BreakOrNot breakAfter) { if (!annotations.isEmpty()) { if (breakBefore.isYes()) { builder.breakToFill(" "); } boolean first = true; for (AnnotationTree annotation : annotations) { if (!first) { builder.breakToFill(" "); } scan(annotation, null); first = false; } if (breakAfter.isYes()) { builder.breakToFill(" "); } } }
private void visitToDeclare( DeclarationKind kind, Direction annotationsDirection, VariableTree node, Optional<ExpressionTree> initializer, String equals, Optional<String> trailing) { sync(node); boolean varargs = VarArgsOrNot.fromVariable(node).isYes(); List<? extends AnnotationTree> varargsAnnotations = ImmutableList.of(); Tree type = node.getType(); declareOne( kind, annotationsDirection, Optional.of(node.getModifiers()), type, VarArgsOrNot.valueOf(varargs), varargsAnnotations, node.getName(), "", equals, initializer, trailing, Optional.<ExpressionTree>absent(), Optional.<TypeWithDims>absent()); }
@Override public String visitAnnotation(AnnotationTree node, Void p) { for (ExpressionTree expressionTree : node.getArguments()) { if (expressionTree instanceof AssignmentTree) { AssignmentTree assignmentTree = (AssignmentTree) expressionTree; ExpressionTree variable = assignmentTree.getVariable(); if (variable instanceof IdentifierTree && ((IdentifierTree) variable).getName().contentEquals(annotationFieldName)) { return scan(expressionTree, p); } } } return null; }
/** * Rotate the list of dimension specifiers until all dimensions with type annotations appear in * source order. * <p> * <p>javac reorders dimension specifiers in method declarations with mixed-array notation, which * means that any type annotations don't appear in source order. * <p> * <p>For example, the type of {@code int @A [] f() @B [] {}} is parsed as {@code @B [] @A []}. * <p> * <p>This doesn't handle cases with un-annotated dimension specifiers, so the formatting logic * checks the token stream to figure out which side of the method name they appear on. */ private static Iterable<List<AnnotationTree>> reorderBySourcePosition( Deque<List<AnnotationTree>> dims) { int lastAnnotation = -1; int lastPos = -1; int idx = 0; for (List<AnnotationTree> dim : dims) { if (!dim.isEmpty()) { int pos = ((JCTree) dim.get(0)).getStartPosition(); if (pos < lastPos) { List<List<AnnotationTree>> list = new ArrayList<>(dims); Collections.rotate(list, -(lastAnnotation + 1)); return list; } lastPos = pos; lastAnnotation = idx; } idx++; } return dims; }
RelationshipAnnotationRenameRefactoringElement(FileObject fo, VariableElement var, AnnotationTree at, AnnotationMirror annotation, String attrValue, int start, int end) { this.fo = fo; this.annotation = annotation; this.attrValue = attrValue; if((end-start)>attrValue.length()){//handle quotes start++; end--; } loc = new int[]{start, end}; this.at = at; this.var = var; }
public ClassTree generate() { ClassTree modifiedClazz = getClassTree(); ModifiersTree methodModifiers = getTreeMaker().Modifiers( getGenerationOptions().getModifiers(), Collections.<AnnotationTree>emptyList() ); FieldInfo em = getEntityManagerFieldInfo(); if (!em.isExisting()){ modifiedClazz = createEntityManager(Initialization.INIT); } MethodTree newMethod = getTreeMaker().Method( methodModifiers, computeMethodName(), getTreeMaker().PrimitiveType(TypeKind.VOID), Collections.<TypeParameterTree>emptyList(), getParameterList(), Collections.<ExpressionTree>emptyList(), "{ " + getMethodBody(em)+ "}", null ); return getTreeMaker().addClassMember(modifiedClazz, importFQNs(newMethod)); }
public ClassTree generate() { ClassTree modifiedClazz = getClassTree(); String body = ""; FieldInfo em = getEntityManagerFieldInfo(); if (!em.isExisting()){ FieldInfo emf = getEntityManagerFactoryFieldInfo(); if (!emf.isExisting()){ modifiedClazz = getTreeMaker().insertClassMember(getClassTree(), getIndexForField(getClassTree()), createEntityManagerFactory(emf.getName())); } body += getEmInitCode(em, emf); } body += getMethodBody(em); ModifiersTree methodModifiers = getTreeMaker().Modifiers( getGenerationOptions().getModifiers(), Collections.<AnnotationTree>emptyList() ); MethodTree newMethod = getTreeMaker().Method( methodModifiers, computeMethodName(), getTreeMaker().PrimitiveType(TypeKind.VOID), Collections.<TypeParameterTree>emptyList(), getParameterList(), Collections.<ExpressionTree>emptyList(), "{ " + body + "}", null ); return getTreeMaker().addClassMember(modifiedClazz, importFQNs(newMethod)); }
protected List<VariableTree> getParameterList(){ if (getGenerationOptions().getParameterType() == null){ return Collections.<VariableTree>emptyList(); } VariableTree parameter = getTreeMaker().Variable( getTreeMaker().Modifiers( Collections.<Modifier>emptySet(), Collections.<AnnotationTree>emptyList() ), getGenerationOptions().getParameterName(), getGenUtils().createType(getGenerationOptions().getParameterType(), getClassElement()), null ); return Collections.<VariableTree>singletonList(parameter); }
protected VariableTree createUserTransaction(){ return getTreeMaker().Variable( getTreeMaker().Modifiers( Collections.<Modifier>singleton(Modifier.PRIVATE), Collections.<AnnotationTree>singletonList(getGenUtils().createAnnotation(RESOURCE_FQN)) ), "utx", //NOI18N getTreeMaker().Identifier(USER_TX_FQN), null); }
protected VariableTree createEntityManagerFactory(String name){ return getTreeMaker().Variable(getTreeMaker().Modifiers( Collections.<Modifier>emptySet(), Collections.<AnnotationTree>emptyList()), name, getTypeTree(ENTITY_MANAGER_FACTORY_FQN), getTreeMaker().MethodInvocation( Collections.<ExpressionTree>emptyList(), getTreeMaker().MemberSelect( getTypeTree("javax.persistence.Persistence"), "createEntityManagerFactory"), // NOI18N Collections.<ExpressionTree>singletonList(getTreeMaker().Literal(getPersistenceUnitName())) ) ); }
public ClassTree generate() { String body = ""; FieldInfo em = getEntityManagerFieldInfo(); if (!em.isExisting()) { body += getEmInitCode(getEntityManagerFactoryFieldInfo()); } body += getInvocationCode(em); ModifiersTree methodModifiers = getTreeMaker().Modifiers( getGenerationOptions().getModifiers(), Collections.<AnnotationTree>emptyList() ); MethodTree newMethod = getTreeMaker().Method( methodModifiers, computeMethodName(), getTreeMaker().PrimitiveType(TypeKind.VOID), Collections.<TypeParameterTree>emptyList(), getParameterList(), Collections.<ExpressionTree>emptyList(), "{ " + body + "}", null ); return getTreeMaker().addClassMember(getClassTree(), importFQNs(newMethod)); }
@Override public Tree visitAnnotation(AnnotationTree tree, Void p) { AnnotationTree n = tree.getKind() == Tree.Kind.ANNOTATION ? make.Annotation(tree.getAnnotationType(), tree.getArguments()) : make.TypeAnnotation(tree.getAnnotationType(), tree.getArguments()); model.setType(n, model.getType(tree)); comments.copyComments(tree, n); model.setPos(n, model.getPos(tree)); return n; }
@Override public Boolean visitAnnotation(AnnotationTree node, TreePath p) { if (p == null) return super.visitAnnotation(node, p); AnnotationTree t = (AnnotationTree) p.getLeaf(); List<? extends ExpressionTree> arguments = t.getArguments(); if (arguments.size() == 1) { ExpressionTree arg = arguments.get(0); if (arg.getKind() == Kind.ASSIGNMENT) { AssignmentTree at = (AssignmentTree) arg; if ( at.getVariable().getKind() == Kind.IDENTIFIER && isMultistatementWildcardTree(at.getExpression()) && ((IdentifierTree) at.getVariable()).getName().contentEquals("value")) { arguments = Collections.singletonList(at.getExpression()); } } } if (!checkLists(node.getArguments(), arguments, p)) return false; return scan(node.getAnnotationType(), t.getAnnotationType(), p); }
public void test175535() throws Exception { prepareTest(); FileObject otherFO = FileUtil.createData(sourceRoot, "test/A.java"); TestUtilities.copyStringToFile(FileUtil.toFile(otherFO), "package test;" + "public class A implements Runnable {" + " @Override" + " public void run() {}" + "}"); TestUtilities.copyStringToFile(FileUtil.toFile(testFO), "public class Test {" + "}"); SourceUtilsTestUtil.compileRecursively(sourceRoot); JavaSource javaSource = JavaSource.forFileObject(testFO); javaSource.runUserActionTask(new Task<CompilationController>() { public void run(CompilationController controller) throws IOException { controller.toPhase(JavaSource.Phase.RESOLVED); TypeElement typeElement = controller.getElements().getTypeElement("test.A"); assertNotNull(typeElement); Element el = typeElement.getEnclosedElements().get(1); assertNotNull(el); assertEquals("run", el.getSimpleName().toString()); TreePath mpath = controller.getTrees().getPath(el); MethodTree mtree = (MethodTree) mpath.getLeaf(); assertNotNull(mtree); List<? extends AnnotationTree> annotations = mtree.getModifiers().getAnnotations(); TypeMirror annotation = controller.getTrees().getTypeMirror(new TreePath(mpath, annotations.get(0))); assertNotNull(annotation); Element e = controller.getTrees().getElement(new TreePath(mpath, annotations.get(0))); assertNotNull(e); assertEquals(((DeclaredType)annotation).asElement(), e); } }, true); }
/** * Creates annotation <code>@org.junit.runner.RunWith</code>. * * @return created annotation */ private AnnotationTree createRunWithSuiteAnnotation( WorkingCopy workingCopy) { TreeMaker maker = workingCopy.getTreeMaker(); /* @RunWith(Suite.class) */ return maker.Annotation( getClassIdentifierTree(ANN_RUN_WITH, workingCopy), Collections.<ExpressionTree>singletonList( maker.MemberSelect( getClassIdentifierTree(ANN_SUITE, workingCopy), "class"))); //NOI18N }
/** */ protected ModifiersTree createModifiersTree(String annotationClassName, Set<Modifier> modifiers, WorkingCopy workingCopy) { TreeMaker maker = workingCopy.getTreeMaker(); AnnotationTree annotation = maker.Annotation( getClassIdentifierTree(annotationClassName, workingCopy), Collections.<ExpressionTree>emptyList()); return maker.Modifiers(modifiers, Collections.<AnnotationTree>singletonList( annotation)); }
@Override public Void visitAnnotation(AnnotationTree tree, EnumSet<UseTypes> d) { // System.err.println("tree.getType()= " + tree.toString()); // System.err.println("tree.getType()= " + tree.getClass()); // TreePath tp = new TreePath(getCurrentPath(), tree.getAnnotationType()); handlePossibleIdentifier(tp, EnumSet.of(UseTypes.CLASS_USE)); super.visitAnnotation(tree, EnumSet.noneOf(UseTypes.class)); //TODO: maybe should be considered return null; }
@Override public Number visitAnnotation(AnnotationTree node, Void p) { List<? extends ExpressionTree> args = resolveMultiParameters(node.getArguments()); AnnotationTree nue = make.Annotation(node.getAnnotationType(), args); rewrite(node, nue); return super.visitAnnotation(node, p); }
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; }
private void cleanField(VariableTree mt) { AnnotationTree t = findFxmlAnnotation(mt.getModifiers()); if (t == null) { return; } if (!isUsed(mt, mt.getModifiers())) { controllerClass = wcopy.getTreeMaker().removeClassMember(controllerClass, mt); return; } wcopy.rewrite( mt.getModifiers(), wcopy.getTreeMaker().removeModifiersAnnotation(mt.getModifiers(), t) ); }
@Override public Void visitAnnotation(AnnotationTree tree, List<Node> d) { List<Node> below = new ArrayList<Node>(); //??? addCorrespondingElement(below); addCorrespondingType(below); addCorrespondingComments(below); super.visitAnnotation(tree, below); d.add(new TreeNode(info, getCurrentPath(), below)); return null; }
@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 ; } } }
private static MethodTree createToStringMethod(WorkingCopy wc, Iterable<? extends VariableElement> fields, String typeName) { TreeMaker make = wc.getTreeMaker(); Set<Modifier> mods = EnumSet.of(Modifier.PUBLIC); List<AnnotationTree> annotations = new LinkedList<>(); if (GeneratorUtils.supportsOverride(wc)) { TypeElement override = wc.getElements().getTypeElement("java.lang.Override"); //NOI18N if (override != null) { annotations.add(wc.getTreeMaker().Annotation(wc.getTreeMaker().QualIdent(override), Collections.<ExpressionTree>emptyList())); } } ModifiersTree modifiers = make.Modifiers(mods, annotations); ExpressionTree exp = make.Literal(typeName + '{'); boolean first = true; for (VariableElement variableElement : fields) { StringBuilder sb = new StringBuilder(); if (!first) { sb.append(", "); } sb.append(variableElement.getSimpleName().toString()).append('='); exp = make.Binary(Tree.Kind.PLUS, exp, make.Literal(sb.toString())); exp = make.Binary(Tree.Kind.PLUS, exp, make.Identifier(variableElement.getSimpleName())); first = false; } StatementTree stat = make.Return(make.Binary(Tree.Kind.PLUS, exp, make.Literal('}'))); //NOI18N BlockTree body = make.Block(Collections.singletonList(stat), false); return make.Method(modifiers, "toString", make.Identifier("String"), Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), body, null); //NOI18N }
private static VariableTree createLoggerField(TreeMaker make, ClassTree cls, CharSequence name, Set<Modifier> mods) { ModifiersTree modifiers = make.Modifiers(mods, Collections.<AnnotationTree>emptyList()); final List<ExpressionTree> none = Collections.<ExpressionTree>emptyList(); IdentifierTree className = make.Identifier(cls.getSimpleName()); MemberSelectTree classType = make.MemberSelect(className, "class"); // NOI18N MemberSelectTree getName = make.MemberSelect(classType, "getName"); // NOI18N MethodInvocationTree initClass = make.MethodInvocation(none, getName, none); final ExpressionTree logger = make.QualIdent(Logger.class.getName()); MemberSelectTree getLogger = make.MemberSelect(logger, "getLogger"); // NOI18N MethodInvocationTree initField = make.MethodInvocation(none, getLogger, Collections.nCopies(1, initClass)); return make.Variable(modifiers, name, logger, initField); // NOI18N }
/** * Adds an annotation to a class. This is equivalent to {@link TreeMaker#addModifiersAnnotation}, * but it creates and returns a new <code>ClassTree, not a new <code>ModifiersTree</code>. * * @param classTree the class to add the annotation to; cannot be null. * @param annotationTree the annotation to add; cannot be null. * @return a new class annotated with the new annotation; never null. */ @SuppressWarnings("unchecked") // NOI18N public ClassTree addAnnotation(ClassTree classTree, AnnotationTree annotationTree) { Parameters.notNull("classTree", classTree); // NOI18N Parameters.notNull("annotationTree", annotationTree); // NOI18N TreeMaker make = getTreeMaker(); return make.Class( make.addModifiersAnnotation(classTree.getModifiers(), annotationTree), classTree.getSimpleName(), classTree.getTypeParameters(), classTree.getExtendsClause(), (List<ExpressionTree>)classTree.getImplementsClause(), classTree.getMembers()); }
/** * Adds an annotation to a variable. This is equivalent to {@link TreeMaker#addModifiersAnnotation}, * but it creates and returns a new <code>VariableTree, not a new <code>ModifiersTree</code>. * * @param variableTree the variable to add the annotation to; cannot be null. * @param annotationTree the annotation to add; cannot be null. * @return a new variable annotated with the new annotation; never null. */ public VariableTree addAnnotation(VariableTree variableTree, AnnotationTree annotationTree) { Parameters.notNull("variableTree", variableTree); // NOI18N Parameters.notNull("annotationTree", annotationTree); // NOI18N TreeMaker make = getTreeMaker(); return make.Variable( make.addModifiersAnnotation(variableTree.getModifiers(), annotationTree), variableTree.getName(), variableTree.getType(), variableTree.getInitializer()); }
public void testCreateAnnotation() throws Exception { TestUtilities.copyStringToFileObject(testFO, "package foo;" + "public class TestClass {" + "}"); runModificationTask(testFO, new Task<WorkingCopy>() { public void run(WorkingCopy copy) throws Exception { GenerationUtils genUtils = GenerationUtils.newInstance(copy); ClassTree classTree = (ClassTree)copy.getCompilationUnit().getTypeDecls().get(0); AnnotationTree annotationTree = genUtils.createAnnotation("java.lang.SuppressWarnings", Collections.singletonList(genUtils.createAnnotationArgument(null, "unchecked"))); ClassTree newClassTree = genUtils.addAnnotation(classTree, annotationTree); annotationTree = genUtils.createAnnotation("java.lang.annotation.Retention", Collections.singletonList(genUtils.createAnnotationArgument(null, "java.lang.annotation.RetentionPolicy", "RUNTIME"))); newClassTree = genUtils.addAnnotation(newClassTree, annotationTree); copy.rewrite(classTree, newClassTree); } }).commit(); runUserActionTask(testFO, new Task<CompilationController>() { public void run(CompilationController controller) throws Exception { TypeElement typeElement = SourceUtils.getPublicTopLevelElement(controller); assertEquals(2, typeElement.getAnnotationMirrors().size()); SuppressWarnings suppressWarnings = typeElement.getAnnotation(SuppressWarnings.class); assertNotNull(suppressWarnings); assertEquals(1, suppressWarnings.value().length); assertEquals("unchecked", suppressWarnings.value()[0]); Retention retention = typeElement.getAnnotation(Retention.class); assertNotNull(retention); assertEquals(RetentionPolicy.RUNTIME, retention.value()); } }); }
public void testCreateAnnotationBooleanArgumentIssue89230() throws Exception { TestUtilities.copyStringToFileObject(testFO, "package foo;" + "@interface Column {" + " boolean nullable();" + "}" + "public class TestClass {" + "}"); runModificationTask(testFO, new Task<WorkingCopy>() { public void run(WorkingCopy copy) throws Exception { GenerationUtils genUtils = GenerationUtils.newInstance(copy); ClassTree classTree = SourceUtils.getPublicTopLevelTree(copy); AnnotationTree annotationTree = genUtils.createAnnotation("foo.Column", Collections.singletonList(genUtils.createAnnotationArgument("nullable", true))); ClassTree newClassTree = genUtils.addAnnotation(classTree, annotationTree); copy.rewrite(classTree, newClassTree); } }).commit(); runUserActionTask(testFO, new Task<CompilationController>() { public void run(CompilationController controller) throws Exception { TypeElement typeElement = SourceUtils.getPublicTopLevelElement(controller); assertEquals(1, typeElement.getAnnotationMirrors().size()); AnnotationMirror columnAnn = typeElement.getAnnotationMirrors().get(0); assertEquals(1, columnAnn.getElementValues().size()); Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> columnAnnNullableElement = columnAnn.getElementValues().entrySet().iterator().next(); assertEquals("nullable", columnAnnNullableElement.getKey().getSimpleName().toString()); assertEquals(true, columnAnn.getElementValues().values().iterator().next().getValue()); } }); }