Reputation: 1
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>
Upvotes: 0
Views: 344
Reputation: 51
So late, I know, but ...
In this snippet:
if (MY_ANNOTATION == node.toString()) ...
Use equals() method to compare two strings:
if (MY_ANNOTATION.equals(node.toString())) ...
Upvotes: 0
Reputation: 627
Omit the @
, just use the annotation name
private final String MY_ANNOTATION = "myAnnotation";
See: How to put annotations on a new line with JavaParser?
Upvotes: 0