/** * In Java variables can be defined like the following: * int i, j, k; * * When mapping fields in xml this is not a problem. However when using annotation on a field, * Each field should be defined separately. This helper will deconstruct these fields such * that later AST analysis will not need to account for field defined on a separate line. */ public static void deconstructMultiDeclarations(Collection<FieldDeclaration> fields) { for (FieldDeclaration field : fields) { ClassOrInterfaceDeclaration parent = (ClassOrInterfaceDeclaration) field.getParentNode(); //these are chained together if (field.getVariables().size() > 1) { int index = parent.getMembers().indexOf(field); parent.getMembers().remove(index); List<FieldDeclaration> deconstructed = new ArrayList<FieldDeclaration>(); for (VariableDeclarator v : field.getVariables()) { FieldDeclaration f = new FieldDeclaration(field.getJavaDoc(), field.getModifiers(), field.getAnnotations(), field.getType(), Collections.singletonList(v)); f.setComment(field.getComment()); f.setParentNode(field.getParentNode()); deconstructed.add(f); } parent.getMembers().addAll(index, deconstructed); } } }
@Override public Node visit(FieldDeclaration _n, Object _arg) { JavadocComment javaDoc = cloneNodes(_n.getJavaDoc(), _arg); List<AnnotationExpr> annotations = visit(_n.getAnnotations(), _arg); Type type_ = cloneNodes(_n.getType(), _arg); List<VariableDeclarator> variables = visit(_n.getVariables(), _arg); Comment comment = cloneNodes(_n.getComment(), _arg); FieldDeclaration r = new FieldDeclaration( _n.getBeginLine(), _n.getBeginColumn(), _n.getEndLine(), _n.getEndColumn(), _n.getModifiers(), annotations, type_, variables ); r.setComment(comment); return r; }