繁体   English   中英

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

[英]Java annotation to execute some code before and after method

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

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

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

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

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

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

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

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

您可以定义注释

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

您添加一个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;
    }
}

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

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

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

您可能希望将AspectJ中的around()建议与注释结合使用,以将around()通知与所有使用注释限定的方法相关联。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM