Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reading Annotations without using instanceof

 
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
Sheriff
Pie
Posts: 49756
69
  • 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: 197
  • 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);
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic