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());
}
8
  • whatever the annotation would be (which I am unaware of) the input would cause NullPointerException Commented Mar 29, 2018 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. Commented Mar 29, 2018 at 13:41
  • 1
    why not simply use a method (or a try/catch)? Commented Mar 29, 2018 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)? Commented Mar 29, 2018 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. Commented Mar 29, 2018 at 14:37

1 Answer 1

1

KludJe is probably what you want.

Sign up to request clarification or add additional context in comments.

3 Comments

Interesting, Minimum is java 8, I will check if that could work
Also, do you know if this uses runtime reflection?
No, only using method references (that's why it require Java 8). See here: github.com/mcdiae/kludje/blob/master/kludje-core/src/main/java/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.