how to replace an annotation with his Attribute with openrewrite?

368 Views Asked by At

To migrate a java API I need to replace an annotation with the value of an attribute and I'm looking for how to do it:

Before:

    @Foo(values = {@Bar(value="one"), @Bar(Value="two")})
    private void stuff() {
    }

After :

    @Foo(values = { "one" ,  "two" })
    private void stuff() {
    }

I tried using the visitAnnotation() method but this should return an annotation and not a literal. If anyone has any idea or advice how to do this.

1

There are 1 best solutions below

0
On

Got it with calling this method upon @Foo's "value" attribute

List<Expression> extractBarAnnotation(@Nullable List<Expression> initializer) {
final List<Expression> barsArray = new ArrayList<>();

for (Expression expression : initializer) {
    J.Annotation innerAnnotation = (J.Annotation) expression;
    List<Expression> newArgs = ListUtils.map(innerAnnotation.getArguments(), it -> {
        if (it instanceof J.Assignment) {
            J.Assignment as = (J.Assignment) it;
            J.Identifier var = (J.Identifier) as.getVariable();
            if ("value".equals(var.getSimpleName())) {
                J.Literal value = (J.Literal) as.getAssignment();
                return value;
            }
        }
        return null;
    });
    barsArray.addAll(newArgs);
}
return barsArray;

}