Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Reading Annotations without using instanceof  RSS feed

 
Patrick Grimard
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just a small question, is there some way that once I've gotten all the annotations on a given class or method that I can read it's values without first checking if the annotation is "instanceof" some annotation type and then casting it?

The following snippet of code is how I've determined how to read the annotation using "instanceof" but I'm curious to know if there's another way of doing it in the event the annotation is of a type you might not be expecting.


 
Patrick Grimard
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I figured it out.


 
Campbell Ritchie
Marshal
Posts: 56205
171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't use == or != for reference types to check whether they are identical. Use the equals() method.
 
Christian Dillinger
Ranch Hand
Posts: 200
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hava a look at the API... You can pass in what Annotation you are looking for and get back that annotation or null.

Sample:
MyAnnotation a = obj.getClass().getAnnotation(MyAnnotation.class);
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!