Java 通过反射识别JAX-RS上的HTTP谓词
我正在编写一些代码,以了解使用Java 通过反射识别JAX-RS上的HTTP谓词,java,reflection,annotations,jax-rs,Java,Reflection,Annotations,Jax Rs,我正在编写一些代码,以了解使用JAX-RS实现的类的元数据,我正在编写一个方法,该方法接受a并返回与该方法相关的HTTP动词,基本上了解它是否用@POST、@GET、@PUT或@DELETE注释 我目前拥有的是: private static String extractHttpVerb(Method method) { if(method.getAnnotation(GET.class) != null) { return "GET"; } else if (m
JAX-RS
实现的类的元数据,我正在编写一个方法,该方法接受a并返回与该方法相关的HTTP动词,基本上了解它是否用@POST
、@GET
、@PUT
或@DELETE
注释
我目前拥有的是:
private static String extractHttpVerb(Method method) {
if(method.getAnnotation(GET.class) != null) {
return "GET";
} else if (method.getAnnotation(POST.class) != null) {
return "POST";
} else if (method.getAnnotation(PUT.class) != null) {
return "PUT";
} else if (method.getAnnotation(DELETE.class) != null){
return "DELETE";
} else {
return "UNKNOWN";
}
}
它工作得很好,但我发现所有这些注释都是用@HttpMethod
注释的,并且有一个值,其名称为字符串。例如:
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("POST")
@Documented
public @interface POST {
}
所以我想知道。有没有办法从我对方法的引用中弄清楚它是否由一个注释注释,而该注释又由另一个特定的注释注释
比如:
boolean annotated = method.hasAnnotationsAnnotatedBy(HttpMethod.class);
PS:我知道这个方法不存在,它只是为了说明我在寻找什么。注释
s由类
es表示,就像任何其他对象一样。就像方法
s一样,类
es也可以反映出来检查注释。比如说
Annotation anno = method.getAnnotation(...);
Class<? extends Annotation> cls = anno.annotationType();
boolean annotHasAnnotation = cls.isAnnotationPresent(...);
public static boolean hasSuperAnnotation(Method method, Class<? extends Annotation> check) {
for (Annotation annotation: method.getAnnotations()) {
if (annotation.annotationType().isAnnotationPresent(check)) {
return true;
}
}
return false;
}
[...]
boolean hasHttpMethod = hasSuperAnnotation(method, HttpMethod.class);
public static String extractHttpVerb(Method method) {
for (Annotation annotation: method.getAnnotations()) {
if (annotation.annotationType().isAnnotationPresent(HttpMethod.class)) {
return annotation.annotationType().getSimpleName();
}
}
return null;
}