从 Method 对象执行嵌套方法调用
Execute nested method calls from Method object
我需要调用以下方法 -
testObj.getA().getB().getC().getD();
以上,testObj.getA() returns 对象 A 具有方法 getB(),returns 对象 B 具有方法 getC(),returns对象 C,它有方法 getD()。
如何使用反射调用它?如果我尝试如下方法对象 -
Method m = testObj.getClass().getMethod("getA().getB().getC().getD(), null));
上面说找不到方法失败。有什么建议吗?
您没有名为 getA().getB().getC().getD()
的方法,因此您无法获取它也就不足为奇了。您有四种不同的方法。
没有什么可以阻止你通过反射调用它们,但你必须将其视为四个单独的方法调用(因为它是):
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);
您可以使用 Apache Commons BeanUtils。
D d = (D)PropertyUtils.getNestedProperty(testObj, "a.b.c.d");
参见here。
我需要调用以下方法 -
testObj.getA().getB().getC().getD();
以上,testObj.getA() returns 对象 A 具有方法 getB(),returns 对象 B 具有方法 getC(),returns对象 C,它有方法 getD()。
如何使用反射调用它?如果我尝试如下方法对象 -
Method m = testObj.getClass().getMethod("getA().getB().getC().getD(), null));
上面说找不到方法失败。有什么建议吗?
您没有名为 getA().getB().getC().getD()
的方法,因此您无法获取它也就不足为奇了。您有四种不同的方法。
没有什么可以阻止你通过反射调用它们,但你必须将其视为四个单独的方法调用(因为它是):
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);
您可以使用 Apache Commons BeanUtils。
D d = (D)PropertyUtils.getNestedProperty(testObj, "a.b.c.d");
参见here。