wood burning stoves 2.0*
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Reading Annotations without using instanceof" Watch "Reading Annotations without using instanceof" New topic

Reading Annotations without using instanceof

Patrick Grimard

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

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

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 38045
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.

MyAnnotation a = obj.getClass().getAnnotation(MyAnnotation.class);
It is sorta covered in the JavaRanch Style Guide.
subject: Reading Annotations without using instanceof
Similar Threads
annotation problem.
Custome Annotation
Java annotations
relational annotations for kin-referencing