栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java注解,用于包装方法

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java注解,用于包装方法

为此,您将需要一些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";         });}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/470101.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号