Java注解可以帮助我? [英] Can Java Annotations help me with this?

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

问题描述

我不知道是否有指定的方法被调用提前一类方法的一种方式。我知道,这样的事情应该是posssible,因为JUnit的有()之前,我想要做的是类似的。

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

基本上我想要一个注释告诉编译器或者富之前,JVM调用的init()()

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

推荐答案

如果您有接口A 你可以用这个接口的实例,其中的 代理 ,并在调用的方法,它的<一个href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/lang/reflect/InvocationHandler.html\"><$c$c>InvocationHandler你可以自由检查​​方法是否被标注,并执行取决于一些动作:

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注解可以帮助我?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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