Can Java Annotations help me with this?

前端 未结 7 571
日久生厌
日久生厌 2021-01-13 14:52

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(),

7条回答
  •  暖寄归人
    2021-01-13 15:25

    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.

提交回复
热议问题