【问题标题】:Java Annotation or Code GenerationJava 注释或代码生成
【发布时间】:2018-03-29 13:35:07
【问题描述】:

给一个嵌套类定义

class A {
   B b;
   public B getB() {
       return b;
   }
}

class B {
   ArrayList<C> list;
   public getListC() {
    return list;
  }
}

class C {
  D d;
  public D getD() {
    return d;
   }
}

class D {
   E e;
   public E getE() {
       return e;
    } 
}

现在假设我有一个 A 类的实例,我想通过 A 的实例访问 E 的实例,如下所示

E someMethod(A a) {
    if (a == null
       || a.getB() == null
       || a.getB().getListC() == null
       || a.getB().getList().isEmpty()
       || a.getB().getList().get(0) == null
       || a.getB().getList().get(0).getD() == null) {
       return null;
     }
    return a.getB().getList().get(0).getD().getE();
}

现在我想知道是否有一种方法可以使用 Annotation 或其他工具自动生成上述代码,这样我就不必重复编写这样的代码。我应该只关注

E someMethod(A a) {
    @AwesomeAnnotation(a.getB().getList().get(0).getD().getE());
}

【问题讨论】:

  • 无论注释是什么(我不知道),输入都会导致 NullPointerException
  • 你应该考虑使用 Optionnals,它会比代码生成更容易。还要考虑这些对象是否有意义,如果没有,那么使用默认值可能是一个更好的解决方案。
  • 为什么不简单地使用方法(或 try/catch)?
  • Java 有方法引用,你可能想写一个方法来做你想做的事。 getOptional(a,A::getB,B::getC,C::getD,D::getE)?
  • @Derlin 捕获 NPE 是非常危险的,如果有一天你用一些计算替换那些简单的 getter,你可能会中断计算并默默吞下异常。

标签: java annotations code-generation java-annotations


【解决方案1】:

KludJe 可能就是你想要的。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2015-11-26
  • 1970-01-01
  • 2011-01-03
  • 1970-01-01
  • 1970-01-01
  • 2011-05-01
  • 1970-01-01
  • 2021-03-25
相关资源
最近更新 更多