0

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();
}
M. A. Kishawy
  • 5,001
  • 11
  • 47
  • 72
  • Possible duplicate thread: http://stackoverflow.com/questions/160970/how-do-i-invoke-a-java-method-when-given-the-method-name-as-a-string – Eldar Agalarov Aug 13 '13 at 17:45

1 Answers1

3

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.
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194