Java注释或代码生成

Java注释或代码生成,java,annotations,code-generation,java-annotations,Java,Annotations,Code Generation,Java Annotations,给出嵌套类定义 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

给出嵌套类定义

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;
    } 
}
现在我想知道是否有一种方法可以使用注释或其他工具自动生成上面的代码,这样我就不必重复编写这样的代码了。我应该只做以下事情

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();
}
E someMethod(A a) {
    @AwesomeAnnotation(a.getB().getList().get(0).getD().getE());
}

可能是你想要的。< / P>不管注释是什么(我都不知道),输入会导致NullPointerExceptionYou应该考虑使用opthnNes,这将比代码生成更容易。还要考虑这些对象为null是否有意义,如果没有,那么使用defaults值可能是更好的解决方案。为什么不简单地使用一个方法(或try/catch)?Java有方法引用,您可能想编写一个方法来做您想要做的事

getOptional(a,a::getB,B::getC,C::getD,D::getE)
?@Derlin捕获NPE是非常危险的,如果有一天你要用一些计算替换那些简单的getter,你可以打断计算并默默地吞下异常。有趣的是,最小值是java 8,我会检查这是否也可以工作,您知道这是否使用运行时反射吗?不,只使用方法引用(这就是为什么它需要Java8)。请看这里: