且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-05-04 00:08:32

你可以使用 AspectJ,或者使用自带 AOP 的 Google Guice.

You may use AspectJ, or use Google Guice which bring its own AOP.

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

The object having the method annotated with your WaitCursor annotation must be injected with Guice.

您定义注释

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

你添加一个 MethodInterceptor :

You add a 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;
    }
}

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

And define a module where you bind the interceptor on any method having your annotation.

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

您可以在此页面