Checking if an annotation is of a specific type

为君一笑 提交于 2019-12-20 09:37:41

问题


I am using reflection to see if an annotation that is attached to a property of a class, is of a specific type. Current I am doing:

if("javax.validation.Valid".equals(annotation.annotationType().getName())) {
   ...
}

Which strikes me as a little kludgey because it relies on a string that is a fully-qualified class-name. If the namespace changes in the future, this could cause subtle errors.

I would like to do:

if(Class.forName(annotation.annotationType().getName()).isInstance(
     new javax.validation.Valid()
)) {
   ...
}

But javax.validation.Valid is an abstract class and cannot be instantiated. Is there a way to simulate instanceof (or basically use isInstance) against an interface or an abstract class?


回答1:


Are you just looking for

if (annotation.annotationType().equals(javax.validation.Valid.class)){}

?




回答2:


Or even simpler:

if (annotation instanceof Valid) { /* ... */ }



回答3:


Just for completeness' sake, another possibility is

if (this.getClass().isAnnotationPresent(MyCustomAnnotation.class)) {



回答4:


Ok, I guess I should have done a little more research before posting the question. I discovered that I could use Class.isAssignableFrom(Class<?> cls):

import javax.validation.Valid;

if(Valid.class.isAssignableFrom(annotation.annotationType())) {
   ...
}

This seems to do the job. I'm not sure if there are any caveats to using this approach, though.




回答5:


Since an annotation is just a class, you can simply use an == compare:

if (annotation.annotationType() == Valid.class) { /* ... */ }


来源:https://stackoverflow.com/questions/3348363/checking-if-an-annotation-is-of-a-specific-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!