Javaparser: how to annotate existing classes?

284 Views Asked by At

I am trying to annotate a class with a custom annotation. I have a simple class (Foo) and a ClassVisitor, which add the annotation to an existing class.

public class Foo{

    public static void main(String[] args) {
        SourceRoot sourceRoot = new SourceRoot(Path.of(".\"));
        CompilationUnit cu = sourceRoot.parse("", "MyFile.java);
        ClassVisitor cv = new ClassVisitor();
        cu.accept(cv, null);
    }
}

class ClassVisitor extends VoidVisitorAdapter<Void> {

    private final String MY_ANNOTATION = "@myAnnotation";
    
    @Override
    public void visit(ClassOrInterfaceDeclaration cid, Void arg) {
        super.visit(cid, arg);
        boolean isAnnotated = false;
        for (Node node : cid.getAnnotations()){
            if (MY_ANNOTATION == node.toString()) {
                isAnnotated = true;
                break;
            }
        }
        if (isAnnotated == false) {
            cid.addAnnotation(MY_ANNOTATION); // error happens here
        }
    }
}

When the code is executed I get the error below:

Exception in thread "main" com.github.javaparser.ParseProblemException: Encountered unexpected token: "@" "@" at line 1, column 1.

Was expecting one of:

"enum"
"exports"
"module"
"open"
"opens"
"provides"
"record"
"requires"
"strictfp"
"to"
"transitive"
"uses"
"with"
"yield"
<IDENTIFIER>
1

There are 1 best solutions below

0
On

Omit the @, just use the annotation name

private final String MY_ANNOTATION = "myAnnotation";

See: How to put annotations on a new line with JavaParser?