8

The CDI class BeanManager has several methods which take parameters of type Annotation or Annotation.... For example BeanManager.getBeans(...).

I would like to know how I'm supposed to pass my annotations as parameters to those methods.

I've tried BeanManager.getBeans(MyBean.class, MyAnnotation.class), but it doesn't work that way. I've seen Class.isAnnotation(), but there's nothing like Class.asAnnotation() to retrieve it as an Annotation type.

Neither BeanManager.getBeans(MyBean.class, @MyAnnotation) worked, nor did BeanManager.getBeans(MyBean.class, (Annotation) MyAnnotation.class).

How can I retrieve my annotation class as type Annotation?

noone
  • 19,520
  • 5
  • 61
  • 76
  • It's not clear what you're trying to do. BeanManager.getBeans(...) returns bean instances of the specified type. If you're trying to read the annotations themselves then you need to use reflection as described by @Hirak. – Steve C May 21 '14 at 12:15

2 Answers2

9

There is an example in the documentation:

beanManager.getBeans(Object.class, new AnnotationLiteral<Any>() {});

Source: 16.6. The Bean interface

palacsint
  • 28,416
  • 10
  • 82
  • 109
  • 2
    That did the trick. It's kind of a weird solution, though. I thought the standard Java API would offer something more convienient. – noone May 21 '14 at 12:17
0

You need to use

getAnnotation(Class annotationClass) Returns this element's annotation for the specified type if such an annotation is present, else null.

Or loop through

getAnnotations() Returns all annotations present on this element.

To get the annotation.

object.getClass().getAnnotations()

javadoc

Hirak
  • 3,601
  • 1
  • 22
  • 33