wood burning stoves*
The moose likes Java in General and the fly likes Reading Annotations without using instanceof Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Reading Annotations without using instanceof" Watch "Reading Annotations without using instanceof" New topic
Author

Reading Annotations without using instanceof

Patrick Grimard
Greenhorn

Joined: Jul 21, 2010
Posts: 2
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

Joined: Jul 21, 2010
Posts: 2
I figured it out.


Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38519
    
  23
Don't use == or != for reference types to check whether they are identical. Use the equals() method.
Christian Dillinger
Ranch Hand

Joined: Jul 20, 2009
Posts: 188
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);
 
wood burning stoves
 
subject: Reading Annotations without using instanceof