Java annotations for pre and post code execution

I am writing a swing application, and I would like the wait cursor to be executed when certain methods are executed. We can do this as follows:

public void someMethod() { MainUI.getInstance().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); //method code MainUI.getInstance().setCursor(Cursor.getDefaultCursor()); } 

What I would like to get is a java annotation that would set the wait cursor before the method execution and return it to its normal state after execution. Thus, the previous example would look something like this.

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

How can i achieve this? Suggestions for other solutions to this problem are also welcome. Thanks!

PS - We use Google Guice in our project, but I don’t understand how to solve the problem using it. If someone provided me with a simple example of a similar problem, that would be very helpful.

+6
source share
2 answers

You can use AspectJ or use Google Guice, which brings your AOP.

An object that has a method annotated using the WaitCursor annotation must be entered using 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 in which you associate an interceptor with any method that has an annotation.

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

You can see more complex use cases for this page.

+10
source

Perhaps you should take a look at using the around () tip in AspectJ in conjunction with your annotation to associate the around () tip with all the methods that match your annotation.

+3
source

Source: https://habr.com/ru/post/924161/


All Articles