加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 23:34:37 所属栏目:Java 来源:网络整理
导读:我正在编写一个swing应用程序,并且我希望在执行某些方法时“等待”光标.我们可以这样做: public void someMethod() { MainUI.getInstance().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); //method code MainUI.getInstance().setCursor(Cur
我正在编写一个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注入.

您可以定义注释

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读