Java注释之前和方法后执行一些code [英] Java annotation to execute some code before and after method

查看:674
本文介绍了Java注释之前和方法后执行一些code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个Swing应用程序,我想有等待光标被执行一些方法的时候。我们可以这样来做:

I'm writing an swing app and i'd like to have 'wait' cursor when some methods are executed. We can do it this way:

public void someMethod() {
    MainUI.getInstance().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    //method code
    MainUI.getInstance().setCursor(Cursor.getDefaultCursor());
}

我想实现的是一个Java注释,这将设置等方法执行前光标和执行后,将其恢复正常。所以previous例子看起来像这样

What I'd like to achieve is a java annotation, that would set wait cursor before method execution and set it back to normal after execution. So previous example would look something like this

@WaitCursor    
public void someMethod() {
    //method code
}

我怎样才能做到这一点?关于解决这一问题的其他变种建议也欢迎。
谢谢!

How can i achieve this? Suggestions about other variants of solving this problem are also welcome. Thanks!

P.S。 - 我们使用谷歌吉斯在我们的项目,但我不明白如何使用它来解决问题。如果有人向我提供类似的问题的简单的例子,那将是非常有益的。

P.S. - We use Google Guice in our project, but i don't get how to solve the problem using it. If someone would provide me with simple example of similar problem, that would be very helpful

推荐答案

您可以使用AspectJ中,或使用谷歌吉斯由此带来了自己的AOP。

You may use AspectJ, or use Google Guice which bring its own AOP.

遇到与 WaitCursor 注解方法的对象必须与吉斯注入。

The object having the method annotated with your WaitCursor annotation must be injected with Guice.

您定义的注释

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface WaitCursor {}

您添加的MethodInterceptor:

You add a MethodInterceptor :

public class WaitCursorInterceptor implements MethodInterceptor {
    public Object invoke(MethodInvocation invocation) throws Throwable {
        // show the cursor
        MainUI.getInstance().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        // execute the method annotated with `@WaitCursor`
        Object result = invocation.proceed();
        // hide the waiting cursor
        MainUI.getInstance().setCursor(Cursor.getDefaultCursor());
        return result;
    }
}

和定义,你拦截器绑定的任何方法让您的注释的模块。

And define a module where you bind the interceptor on any method having your annotation.

public class WaitCursorModule extends AbstractModule {
    protected void configure() {
        bindInterceptor(Matchers.any(), Matchers.annotatedWith(WaitCursor.class), new WaitCursorInterceptor());
    }
}

您可以看到在此页面

这篇关于Java注释之前和方法后执行一些code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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