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

使用注释进行异常处理?

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

使用注释进行异常处理?

这应该是一个低层的过程,并不意味着我们不能与当前层有相同的事物,但是它可能需要一堆代码,并且会使系统有些复杂。但是我的建议是这样的(我希望我做对了),首先为想要处理异常的人定义一个接口,像这样。

interface ExceptionHandler{  void handleException(Throwable t);}

然后为user(API)提供注释以标记其方法可能会引发某些异常。

@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.ANNOTATION_TYPE)@interface Catch{  public Class<? extends ExceptionHandler> targetCatchHandler();  public Class<? extends Throwable> targetException() default Exception.class;}@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)@interface CatchGroup{  public Catch[] catchers();}

接下来,我们需要一个接口来开始调用可能引发异常的方法,类似这样。

interface Caller{  void callMethod()throws Throwable;}

那么您需要一个负责并管理执行流程并调用可能的异常处理程序的人

class MethodCaller{    public static void callMethod(Caller instance)      throws Exception {    Method m = instance.getClass().getMethod("callMethod");    Annotation as[] = m.getAnnotations();    Catch[] li = null;    for (Annotation a : as) {      if (a.annotationType().equals(CatchGroup.class)) {        li = ((CatchGroup) a).catchers();      }      // for(Catch cx:li){cx.targetException().getName();}    }    try {      instance.callMethod();    } catch (Throwable e) {      Class<?> ec = e.getClass();      if (li == null) {        return;      }      for (Catch cx : li) {        if (cx.targetException().equals(ec)) {          ExceptionHandler h = cx.targetCatchHandler().newInstance();          h.handleException(e);          break;        }      }    }  }}

最后,让我们举个例子,它对我来说很好用,很酷。异常处理程序。

public class Bar implements ExceptionHandler{//the class who handles the exception  @Override  public void handleException(Throwable t) {    System.out.println("Ta Ta");    System.out.println(t.getMessage());  }}

和方法调用者。

class Foo implements Caller{//the class who calls the method  @Override  @CatchGroup(catchers={       @Catch(targetCatchHandler=Bar.class,targetException=ArithmeticException.class),      @Catch(targetCatchHandler=Bar.class,targetException=NullPointerException.class)})  public void callMethod()throws Throwable {    int a=0,b=10;    System.out.println(b/a);  }  public static void main(String[] args) throws Exception {    Foo foo=new Foo();    MethodCaller.callMethod(foo);  }}

如您所见,用户必须按该

callmethod()
方法调用方法,您还可以省略
Caller
接口,并使用注释在一个类中声明一个以上的方法,该方法需要大量额外的代码。我希望我能帮上忙。



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

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

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