3

I have a method in my MainClass that returns an integer value. I send this method to another Class, which tries to invoke this method. Like this:

newVal = (Integer) calcM.invoke(receiver, start+i);

But I don't know what to put as receiver? this doesn't work.

4

3 回答 3

4

在您的情况下receiver,接收器对象将调用它的方法。

像这样想,当你说 时,myObject.myMethod它会调用myMethodmyObject与invoke相同,它需要知道在哪个对象上调用该方法。所以在这个例子中,你会传入myObject调用。

于 2013-05-28T13:33:27.843 回答
3

你的问题暗示的样子,你receiver会是这样的:

   Method receiver = MainClass.class.getMethod("methodOfMainClass", int.class);    

听起来你的方法calcM.invoke的签名就像,

 public Integer invoke(Method method, int number)

所以可以打电话,

  newVal = (Integer)calcM.invoke(receiver, start+i);
于 2013-05-28T13:46:44.827 回答
2

如果您的方法是静态的,则正确的接收器是null. 否则,它就是您要调用该方法的对象。

于 2013-05-28T13:42:54.847 回答