Java注释在方法之前和之后执行一些代码

Sta*_*tan 9 java swing annotations cursor

我正在编写一个swing应用程序,并且我希望在执行某些方法时"等待"光标.我们可以这样做:

public void someMethod() {
    MainUI.getInstance().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    //method code
    MainUI.getInstance().setCursor(Cursor.getDefaultCursor());
}
Run Code Online (Sandbox Code Playgroud)

我想要实现的是一个java注释,它会在方法执行之前设置等待光标,并在执行后将其设置回正常状态.所以前面的例子看起来像这样

@WaitCursor    
public void someMethod() {
    //method code
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能实现这一目标?关于解决这个问题的其他变体的建议也是受欢迎的.谢谢!

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

Ale*_*lex 12

您可以使用AspectJ,或使用自带AOP的Google Guice.

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

您可以定义注释

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface WaitCursor {}
Run Code Online (Sandbox Code Playgroud)

您添加一个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;
    }
}
Run Code Online (Sandbox Code Playgroud)

并定义一个模块,您可以在任何具有注释的方法上绑定拦截器.

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

您可以在此页面上看到更多高级用法