1

Give a nested class definition

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;
    } 
}

Now let's say that I have an Instance of Class A and I want to get access to an instance of E through A's instance like following

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();
}

Now I want to know if there is a way to automatically genererate the above code using Annotation or some other tool so that I don't have to repeaditly write such a code. I should only be doing following

E someMethod(A a) {
    @AwesomeAnnotation(a.getB().getList().get(0).getD().getE());
}
Big O
  • 417
  • 1
  • 5
  • 14
  • whatever the annotation would be (which I am unaware of) the input would cause NullPointerException – Sharon Ben Asher Mar 29 '18 at 13:41
  • You should consider using Optionnals, it's going to be easier than code generation. Also think about whether or not it make sense for these objects to be null, if not then using defaults value might be a better solution. – Nyamiou The Galeanthrope Mar 29 '18 at 13:41
  • 1
    why not simply use a method (or a try/catch)? – Derlin Mar 29 '18 at 13:42
  • Java has method references, you may want to write a method that do what you want. `getOptional(a,A::getB,B::getC,C::getD,D::getE)`? – user202729 Mar 29 '18 at 13:55
  • 1
    @Derlin catch of NPE is very dangerous, if you were to replace those simple getter one day with some computation, you could break in the computation and swallow the exception silently. – Nyamiou The Galeanthrope Mar 29 '18 at 14:37
  • @user202729 correct me if I am wrong, however, wouldn't Optional require changing the fields declaration of nested types to like Optional? What if nested classes are part of a thirdparty library and can't be changed? – Big O Mar 29 '18 at 14:48
  • Should you @NyamiouTheGaleanthrope instead? ... – user202729 Mar 29 '18 at 14:50
  • That's why I suggest KludJe as the answer because it also works for all cases, but if it's your code you should consider Optionnals. – Nyamiou The Galeanthrope Mar 29 '18 at 15:36

1 Answers1

1

KludJe is probably what you want.