Java Annotations 能帮我解决这个问题吗? [英] Can Java Annotations help me with this?

查看:23
本文介绍了Java Annotations 能帮我解决这个问题吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以指定在类方法之前调用方法.我知道这样的事情应该是可能的,因为 JUnit 有 before(),我想做的是类似的.

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

基本上我想要一个注释在 foo() 之前告诉编译器或 jvm 调用 init()

Basically I want an annotation to tell either the compiler or the jvm call init() before foo()

推荐答案

如果你有 interface A 你可以用 Proxy 和里面的 invokeInvocationHandler你可以自由检查方法是否被注释并根据它执行一些操作:

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));

或者您可以尝试使用 AspectJ 的之前"建议.它将类似于下一个:

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.

这篇关于Java Annotations 能帮我解决这个问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆