所以我有一个代码:
@Path("/foo")
public class Hello {
@GET
@Produces("text/html")
public String getHtml(@Context Request request, @Context HttpServletRequest requestss){
...
}
我使用AspectJ来捕获对getHtml
方法的所有调用。我想在我的建议中将参数传递给@Produces
和@Path
,在这种情况下是"/foo"
和"text/html"
。我怎么能用反射来做呢?
答案 0 :(得分:33)
获取@Path
参数的值:
String path = Hello.class.getAnnotation(Path.class).value();
同样,您持有Method
getHtml
Method m = Hello.class.getMethod("getHtml", ..);
String mime = m.getAnnotation(Produces.class).value;
答案 1 :(得分:4)
注释基于接口逻辑。您需要调用它的有效成员来检索值。
定义
public @interface Produces {
String type();
}
阅读示例
for (Method m: SomeClass.class.getMethods() {
Produces produce = m.getAnnotation(Produces.class);
if (produce != null)
System.out.println(produce.type());
}
是。您必须使用反射来访问方法定义。您可以使用Class#MgetMethods()来获取方法
的定义对于对象,您可以调用obj.getClass()
来获取类定义。