Java注解在方法前后执行一些代码

标签 java swing annotations mouse-cursor

我正在编写一个 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
}

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

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

最佳答案

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

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

你定义你的注解

@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;
    }
}

并定义一个模块,您可以在其中将拦截器绑定(bind)到任何具有您的注释的方法上。

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

您可以在 this page 上看到更多高级用途

关于Java注解在方法前后执行一些代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12195015/

相关文章:

Java Swing UI 替换

Java 作用域构造不能用类型使用进行注释

java - Java/Scala 中无效的 ZoneDateTime 解析

java - 配置 Jackson 在 Spring Boot 2.0.0.M1 中使用 SNAKE_CASE "globally"

java - 在 Java 中转换 ArrayList

Java邮件 : TLS on port 25 with separate truststore possible?

java - 为什么调用 JFrame.pack() 会增加额外的空间?

java - Java 10 上的 Swing 问题

iphone - 将同名的注释分组

android - 在 AndroidTestCase 中使用 @Ignore