我有一个AnnotationExpr
,如何获取参数及其注释值(例如@UnityBridge(fullClassName = "test")
- 如何获取fullClassName
参数的值)。 JavaParser是否支持此功能?
我必须接受另一位访客吗?在这种情况下哪一个?
答案 0 :(得分:4)
迟到的回答,我遇到了同样的问题,只是将AnnotationExpr
投射到以下之一:
MarkerAnnotationExpr
(无参数),
SingleMemberAnnotationExpr
(对于单个参数),
NormalAnnotationExpr
(适用于多个参数)。
您可能需要instanceof
来确定当前的注释类型。
答案 1 :(得分:0)
我更喜欢没有instanceof的这种方法,而是按类型搜索子节点,尽管你仍然需要区分单个参数而没有键来找到参数"值":
Date.dayHours()
答案 2 :(得分:0)
最简单的解决方案是:
import com.github.javaparser.StaticJavaParser
import com.github.javaparser.ast.CompilationUnit
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration
import com.github.javaparser.ast.expr.AnnotationExpr
import com.github.javaparser.ast.NodeList
import com.github.javaparser.ast.expr.MemberValuePair
// Annotation
public @interface AnnotationName {
String argumentName();
}
// Class with this annotation
@AnnotationName(argumentName = "yourValue")
public class ClassWithAnnotationName {}
// Parse class with annotation
CompilationUnit compilationUnit = StaticJavaParser.parse(sourceFile);
Optional<ClassOrInterfaceDeclaration> classInterfaceForParse = compilationUnit.getInterfaceByName("ClassWithAnnotationName");
// Get annotation by name
final AnnotationExpr messageQueueKeyAnnotation =
classInterfaceForParse.get().getAnnotationByName("AnnotationName").get();
// Get all parameters. It doesn't matter how many.
final NodeList<MemberValuePair> annotationParameters = messageQueueKeyAnnotation.toNormalAnnotationExpr().get().pairs;
// Read annotation parameter from the list of all parameters
final String argumentName = annotationParameters.get(0).value;