This discussion is archived
3 Replies Latest reply: Nov 15, 2010 3:07 PM by 796440 RSS

Reflection and method chaining

814681 Newbie
Currently Being Moderated
Hello,

I'm doing some work with reflection and am using the class java.lang.reflect.Method to invoke methods (using the, er, "invoke" method).

One aspect of the work I'm doing involves method chaining, e.g. myObject.aMethod().anotherMethod().yetAnotherMethod();

Looking at the API docs, the invoke() method only seems to accept a single method call and its associated parameters. Can method chaining be modelled using reflection?

Thanks for any thoughts.
  • 1. Re: Reflection and method chaining
    796440 Guru
    Currently Being Moderated
    811678 wrote:
    Hello,

    I'm doing some work with reflection and am using the class java.lang.reflect.Method to invoke methods (using the, er, "invoke" method).

    One aspect of the work I'm doing involves method chaining, e.g. myObject.aMethod().anotherMethod().yetAnotherMethod();

    Looking at the API docs, the invoke() method only seems to accept a single method call and its associated parameters. Can method chaining be modelled using reflection?

    Thanks for any thoughts.
    If you mean you want to use method chaining in your Java code's use of reflection, like invoke().invoke().invoke(), then no, you cannot.

    If you mean you're parsing some string and using it to reflectively invoke a method named by that string, then sure, just add the appropriate parsing code and apply the results to the underlying reflective code just like you're doing for a single method name and arg list.
  • 2. Re: Reflection and method chaining
    814681 Newbie
    Currently Being Moderated
    Thank you for your swift and helpful reply. I mean the former, unfortunately. I will have to rethink my approach.
  • 3. Re: Reflection and method chaining
    796440 Guru
    Currently Being Moderated
    811678 wrote:
    Thank you for your swift and helpful reply. I mean the former, unfortunately. I will have to rethink my approach.
    Yeah, if you stop and think about it, given that invoke() is a method of the Method class, it would only work if invoke() returned a Method object as well.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points