Java注释用于包装的方法 [英] Java annotation for wrapping a method

查看:101
本文介绍了Java注释用于包装的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多样板code的,基本上遵循以下模式:

I have a lot of boilerplate code that basically follows this pattern:

function doSomething() {
  try {
    [implementation]
    [implementation]
    [implementation]
    [implementation]
  } catch (Exception e) {
    MyEnv.getLogger().log(e);
  } finally {
    genericCleanUpMethod();
  }
}

我喜欢创建自己的注解来清洗我的code了一下:

I'd love to create my own annotation to clean my code up a bit:

@TryCatchWithLoggingAndCleanUp
function doSomething() {
  [implementation]
  [implementation]
  [implementation]
  [implementation]
}

中的方法签名大相径庭(取决于实际执行的方法),但样板的try / catch /最后的部分是始终不变的。

The method signatures vary wildly (depending on the actual implementation of the method), but the boilerplate try/catch/finally part is always the same.

注释我心目中会自动与整个包住注解的方法的内容的try ... catch ...最后的喧闹。

The annotation I have in mind would automatically wrap the contents of the annotated method with the whole try...catch...finally hoopla.

我已经搜查高和低一个简单的方法来做到这一点,但都一无所获。我不知道,也许我只是不能看到树林里的所有注解的树。

I've searched high and low for a straightforward way to do this, but have found nothing. I dunno, maybe I just can't see the woods for all the annotated trees.

这是我如何实现这样的注解任何指针将大大AP preciated。

Any pointers on how I might implement such an annotation would be greatly appreciated.

推荐答案

要做到这一点,你就需要一些AOP框架,使用代理在你的方法。这个代理将捕获异常并执行finally块。坦率地说,如果你不使用框架,支持AOP已经,我不知道我会用一个只是为了节省这几行OD code。

To do this, you would need some AOP framework that would use a proxy around your method. This proxy would catch the exception and execute the finally block. Quite frankly, if you don't use a framework supporting AOP already, I'm not sure I would use one just to save these few lines od code.

您可以使用以下方式来做到这一点更优雅的方式,虽然:

You could use the following pattern to do this in a more elegant way, though:

public void doSomething() {
    logAndCleanup(new Callable<Void>() {
        public Void call() throws Exception {
            implementationOfDoSomething();
            return null;
        }
    });
}

private void logAndCleanup(Callable<Void> callable) {
    try {
        callable.call();
    } 
    catch (Exception e) {
        MyEnv.getLogger().log(e);
    } 
    finally {
        genericCleanUpMethod();
    }
}

我只是用

可赎回&LT;无效&GT; 作为一个接口,但你可以定义自己的命令接口:

I just used Callable<Void> as an interface, but you could define your own Command interface:

public interface Command {
    public void execute() throws Exception;
}

,从而避免需要使用一个通用的可赎回&LT;无效方式&gt; 从可赎回返回null

and thus avoid the need to use a generic Callable<Void> and return null from the Callable.

编辑:如果你想返回从你的方法什么的,然后进行 logAndCleanup()方法通用。这里有一个完整的例子:

in case you want to return something from your methods, then make the logAndCleanup() method generic. Here's a complete example:

public class ExceptionHandling {
    public String doSomething(final boolean throwException) {
        return logAndCleanup(new Callable<String>() {
            public String call() throws Exception {
                if (throwException) {
                    throw new Exception("you asked for it");
                }
                return "hello";
            }
        });
    }

    public Integer doSomethingElse() {
        return logAndCleanup(new Callable<Integer>() {
            public Integer call() throws Exception {
                return 42;
            }
        });
    }

    private <T> T logAndCleanup(Callable<T> callable) {
        try {
            return callable.call();
        }
        catch (Exception e) {
            System.out.println("An exception has been thrown: " + e);
            throw new RuntimeException(e); // or return null, or whatever you want
        }
        finally {
            System.out.println("doing some cleanup...");
        }
    }

    public static void main(String[] args) {
        ExceptionHandling eh = new ExceptionHandling();

        System.out.println(eh.doSomething(false));
        System.out.println(eh.doSomethingElse());
        System.out.println(eh.doSomething(true));
    }
}

编辑:和与Java 8中,包裹code可有点prettier:

EDIT : And with Java 8, the wrapped code can be a bit prettier :

public String doSomething(final boolean throwException) {
    return logAndCleanup(() -> {                
        if (throwException) {
            throw new Exception("you asked for it");
        }
        return "hello";                
    });
}

这篇关于Java注释用于包装的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆