我有一个AnnotationExpr,如何获取参数及其注释的值(例如,@UnityBridge(fullClassName = "test") -如何获得fullClassName参数的值)。JavaParser支持这个吗?
我必须接受另一位客人吗?在这个案子里哪一个?
发布于 2016-07-27 08:15:06
延迟回答时,我遇到了同样的问题,只是将AnnotationExpr转换为以下问题之一:
MarkerAnnotationExpr (对于无参数),
SingleMemberAnnotationExpr (用于单个参数),
NormalAnnotationExpr (用于多个参数)。
您可能需要instanceof来确定当前的注释类型。
发布于 2019-09-06 13:08:43
最简单的解决办法是:
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;https://stackoverflow.com/questions/37208935
复制相似问题