755
755

Reputation: 3081

Guice Multibinder for Annotations with Specific Value

I know that I can do a Guice multibind with a specific annotation as follows

Multibinder.newSetBinder(binder(), Bound.class, Annotation.class);

But can I do a more specific multibind on classes that are not only annotated with Annotation.class but also have a specific value, e.g. @Annotation("type1")?

Upvotes: 0

Views: 1242

Answers (1)

Fred
Fred

Reputation: 101

In this case you could implement your annotation and pass an instance of it to the Multibinder static factory method:

  static class YourAnnotationImpl implements YourAnnotation {

    private final String value;


    YourAnnotationImpl(String value) {
      this.value = value;
    }

    @Override public String value() {
      return value;
    }

    @Override public Class<? extends Annotation> annotationType() {
      return YourAnnotation.class;
    }

    @Override public String toString() {
      return "@" + YourAnnotation.class.getName() + "(value=" + value + ")";
    }

    @Override public boolean equals(Object o) {
      return o instanceof YourAnnotationImpl
          && ((YourAnnotationImpl) o).value().equals(value());
    }

    @Override public int hashCode() {
      return (127 * "value".hashCode()) ^ value.hashCode();
    }

  }
   ...

   Multibinder.newSetBinder(binder(), Bound.class, new YourAnnotationImpl("type1");

Upvotes: 3

Related Questions