在这个例子中是否可以使用javassist获取Spring方法注释?
@RequestMapping(value={"/start"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
public String showForm(Model model, HttpServletRequest request)
答案 0 :(得分:0)
我希望我理解这个问题,你可以使用Java反射来解决它。
如果您知道方法和注释:
RequestMapping annotation = YourController.class.getMethod("showForm", Model.class, HttpServletRequest.class).getAnnotation(RequestMapping.class);
RequestMethod[] requestMethods = annotation.method();
如果您想要检索特定方法的所有注释:
Annotation[] annotations = YourController.class.getMethod("showForm", Model.class, HttpServletRequest.class).getAnnotations();
如果要检索具有给定注释的所有方法:
List<Method> methods = new ArrayList<>();
for (final Method method : YourController.class.getMethods()) {
if (method.getAnnotation(RequestMapping.class) != null) {
methods.add(method);
}
}
或Java 8方式:
List<Method> methods = Arrays.stream(YourController.class.getMethods()).filter(method -> method.getAnnotation(RequestMapping.class) != null).collect(Collectors.toList());
答案 1 :(得分:0)
例如,
import javassist.bytecode.annotation.Annotation;
:
CtMethod m = ... ;
MethodInfo minfo = m.getMethodInfo();
AnnotationsAttribute attr = (AnnotationsAttribute)
minfo.getAttribute(AnnotationsAttribute.invisibleTag);
Annotation an = attr.getAnnotation("Author");
String s = ((StringMemberValue)an.getMemberValue("name")).getValue();
System.out.println("@Author(name=" + s + ")");
摘自官方文档:https://www.javassist.org/html/javassist/bytecode/AnnotationsAttribute.html