Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if an annotation is of a specific type

Tags:

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?

like image 538
Vivin Paliath Avatar asked Jul 27 '10 21:07

Vivin Paliath


2 Answers

Are you just looking for

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

?

like image 66
Affe Avatar answered Oct 28 '22 19:10

Affe


Or even simpler:

if (annotation instanceof Valid) { /* ... */ } 
like image 33
yurez Avatar answered Oct 28 '22 21:10

yurez