Can Java Annotations help me with this?

annotations, java

Solution

If you have `interface A` you can wrap instances of this interface with `Proxy` and inside `invoke` method of its `InvocationHandler` you are free to check whether method is annotated and perform some actions depending on that:

class Initalizer implements InvocationHandler {
    private A delegate;
    Initializer(A delegate) {
        this.delegate = delegate;
    }

    public Object invoke(Object proxy, Method method, Object[] args) {
        if (method.isAnnotationPresent(magic.class)) {
            magic annotation = method.getAnnotation(magic.class);
            delegate.init(magic.arg);
        }
        method.invoke(delegate, args);
    }
} 
A realA = ...;
A obj = Proxy.newProxyInstance(A.class.getClassLoader(), new Class[] {A.class}, new Initializer(realA));

Or you can try using "before" advice of AspectJ. It will be something like the next:

@Aspect
public class Initializer {
    @Before("@annotation(your.package.magic) && target(obj) && @annotation(annotation)")
    private void initialize(A obj, magic annotation) {             
         a.init(annotation.arg);
    }
}

I'm not sure that snippets are working, they just illustrate idea.

Problem

I'm wondering if there is a way to specify that a method gets called in advance of a class method. I know something like this should be posssible, since JUnit has before(), what I want to do is similar. Here is a concrete example of what I'd like to do ``` class A { public void init(int a) { System.out.println(a); } @magic(arg=1) public void foo() { // } public static void main() { A a = new A(); a.foo(); } } //Output: 1 ``` Basically I want an annotation to tell either the compiler or the jvm call init() before foo()

Original source