Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
728 views
in Technique[技术] by (71.8m points)

swing - Java annotation to execute some code before and after method

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.getInstance().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    //method code
    MainUI.getInstance().setCursor(Cursor.getDefaultCursor());
}

What I'd like to achieve is a java annotation, that would set wait cursor before method execution and set it back to normal after execution. So previous example would look something like this

@WaitCursor    
public void someMethod() {
    //method code
}

How can i achieve this? Suggestions about other variants of solving this problem are also welcome. Thanks!

P.S. - We use Google Guice in our project, but i don't get how to solve the problem using it. If someone would provide me with simple example of similar problem, that would be very helpful

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...