Java annotation to execute some code before and after method

前端 未结 2 1121
再見小時候
再見小時候 2020-12-10 04:25

I\'m writing an swing app and i\'d like to have \'wait\' cursor when some methods are executed. We can do it this way:

public void someMethod() {
    MainUI         


        
相关标签:
2条回答
  • 2020-12-10 05:02

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

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

    You define your annotation

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

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

    You can see more advanced uses on this page

    0 讨论(0)
  • 2020-12-10 05:07

    You might want to look at using around() advice in AspectJ in conjunction with your annotation to associate the around() advice with all methods that are qualified with your annotation.

    0 讨论(0)
提交回复
热议问题