M. A. Kishawy
M. A. Kishawy

Reputation: 5079

How can I use Java reflection to invoke a method on a reference variable?

Class X is being used inside class Y. Class X has a function xMethod that is not used inside class Y. Can I use reflection on Class Y to invoke the xMethod on Y's xInternalVar?How?

class X  {
    void xMethod (){ 
    //some code
}

class Y {
    X xInternalVar = new X();
}

Upvotes: 0

Views: 97

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500755

Yes - you've just got two steps here:

  1. Fetch the value of xIntervalVar - use Class.getDeclaredField to get at the relevant field in Y, then get the value of it for the relevant instance of Y
  2. Call xMethod on the instance of X - use Class.getDeclaredMethod to get at the relevant method in X, then invoke the method using the value returned by step 1.

Upvotes: 3

Related Questions