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

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

问题描述

我正在编写一个 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 注释,它会在方法执行之前设置等待光标,并在执行后将其设置为正常.所以前面的例子看起来像这样

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!

附言- 我们在我们的项目中使用 Google Guice,但我不知道如何使用它来解决问题.如果有人能为我提供类似问题的简单示例,那将非常有帮助

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 的 Google Guice.

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

具有使用 WaitCursor 注释的方法注释的对象必须注入 Guice.

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注解在方法之前和之后执行一些代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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