0

I'm new to cglib, but it seems like the right tool for the job, so here goes:

Suppose I have an annotation classes Foo and Bar, and an enum class B, such that Foo and Bar are declared as follows:

public @interface Foo {
    public B value();
}

public @interface Bar {
    public B value();
}

Now, suppose I have this:

public class AnnotationImpl<A extends Annotation, B extends Enum<B>> {
    public AnnotationImpl(Class<A> annotationClass, B value);
    // value() returns value, annotationType() returns annotationClass
    // Implement equals(), hashCode(), toString() as specified
}

It seems repetitive to have to subclass AnnotationImpl for both Foo and Bar when they are more or less identical; is it possible to use cglib to have a method makeImpl() taking an an annotation class that returns an AnnotationImpl that implements that annotation class? eg. makeImpl(Foo.class, B.ONE) returns a Foo backed by AnnotationImpl(Foo.class, B.ONE)?

Kelvin Chung
  • 1,327
  • 1
  • 11
  • 23

1 Answers1

1

If you only want to return the value, implementing an annotation with cglib is quite trivial. However, if you want to correctly implement the hashCode, equals and toString methods, it requires slightly more work.

For doing so, you do not even need cglib, you can simply work with the JDK proxies that ship with the standard class library. This would work as follows:

<T> makeImpl(Class<T> type, Object value) {
  return Proxy.newProxyInstance(type.getClassLoader(),
                                new Class<?>[] { type },
                                new InvocationHandler() {
                                  @Override
                                  Object invoke(Object proxy, 
                                                Method method, 
                                                Object[] args) {
                                    // Fails when incompatible, e.g. hashCode method
                                    // or annotation with incompatible signature.
                                    return value;
                                  }
                                });
}

If you wanted to implement an generic proxy for annotations, look at my libary's AnnotationInvocationHandler which implements such a handler. (My library Byte Buddy does things similar to cglib.)

Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192