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

我正在编写一个swing应用程序,并且我想在执行某些方法时使用’wait’光标。 我们可以这样做:

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()通知与所有使用注释限定的方法相关联。