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

前端之家收集整理的这篇文章主要介绍了Java注释在方法之前和之后执行一些代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在编写一个swing应用程序,并且我希望在执行某些方法时“等待”光标.我们可以这样做: @H_301_2@public void someMethod() { MainUI.getInstance().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); //method code MainUI.getInstance().setCursor(Cursor.getDefaultCursor()); }

我想要实现的是一个java注释,它会在方法执行之前设置等待光标,并在执行后将其设置回正常状态.所以前面的例子看起来像这样

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

我怎样才能实现这一目标?关于解决这个问题的其他变体的建议也是受欢迎的.
谢谢!

附: – 我们在项目中使用Google Guice,但我不知道如何使用它来解决问题.如果有人会向我提供类似问题的简单示例,那将非常有帮助

解决方法

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

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

您可以定义注释

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

添加一个MethodInterceptor:

@H_301_2@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; } }

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

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

您可以在this page上看到更多高级用途

猜你在找的Java相关文章