Reputation: 703
I need to make a call to following method -
testObj.getA().getB().getC().getD();
Above, testObj.getA() returns object A which has a method getB(), which returns object B that has method getC(), which returns object C and it has method getD().
How can I invoke it using reflection? If I try Method object as following -
Method m = testObj.getClass().getMethod("getA().getB().getC().getD(), null));
Above fails saying the method is not found. Any suggestions?
Upvotes: 1
Views: 1850
Reputation:
You can use Apache Commons BeanUtils.
D d = (D)PropertyUtils.getNestedProperty(testObj, "a.b.c.d");
See here.
Upvotes: 2
Reputation: 58909
You don't have a method called getA().getB().getC().getD()
, so it's no surprise you can't get it. You have four separate methods.
There's nothing stopping you from calling them all through reflection, but you have to treat it as four separate method calls (because it is):
TypeOfA a = testObj.getClass().getMethod("getA").invoke(testObj);
TypeOfB b = TypeOfA.class.getMethod("getB").invoke(a);
TypeOfC c = TypeOfB.class.getMethod("getC").invoke(b);
TypeOfD d = TypeOfC.class.getMethod("getD").invoke(c);
Upvotes: 4