javaparsingjavaparser

JavaParser add Annotation with single value


I'm tryng to parse a java file to add annotation to the classes. I have a class like

Class A{
}

And i want it to become like

@Foo(Bar)
ClassA{
}

At the moment i'm using a visitor with like:

public void visit(ClassOrInterfaceDeclaration n, Object arg){
        n.addAnnotation("Foo");
        SingleMemberAnnotationExpr expr=(SingleMemberAnnotationExpr)n.getAnnotation(0);
    }

Now i have the annotation but i don't get how you set the value


Solution

  • You can use ClassOrInterfaceDeclaration.addSingleMemberAnnotation(String name , String value) like below :

    node.addSingleMemberAnnotation("Foo", "\"/a/b/c\"");
    

    You can refer from this java doc : https://www.javadoc.io/doc/com.github.javaparser/javaparser-core/3.3.2/com/github/javaparser/ast/nodeTypes/NodeWithAnnotations.html#addSingleMemberAnnotation-java.lang.String-java.lang.String-