为此,您将需要一些AOP框架,该框架将在您的方法周围使用代理。该代理将捕获异常并执行finally块。坦率地说,如果您还没有使用支持AOP的框架,我不确定我是否会只使用它来保存这几行od代码。
但是,您可以使用以下模式以更优雅的方式执行此 *** 作:
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(); }}
我只是用作
Callable<Void>接口,但是您可以定义自己的
Command接口:
public interface Command { public void execute() throws Exception;}
因此避免了使用泛型
Callable<Void>并从Callable返回null 的需要。
编辑:如果您想从您的方法返回一些东西,然后使该
logAndCleanup()方法通用。这是一个完整的示例:
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,包装的代码可以有点漂亮:
public String doSomething(final boolean throwException) { return logAndCleanup(() -> { if (throwException) { throw new Exception("you asked for it"); } return "hello"; });}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)