您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

您可以使用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());
    }
}

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

java 2022/1/1 18:17:23 有668人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶