0

Is there any way to access a variable of an overridden class if a nested private method is involved?

In partiular, I want to know the value of String foo inside class B after the rename function was performend (see example below). I do not intend to change any of the functionality of the code of class A, this is solely about getting the value somehow.

I am free to edit class B but changing class A would only be an option to me if there really is no other way to achieve this.

public abstract class A {
  protected void methodA() {
     String foo = "bla";
     foo = renameFunction(foo);
  }

  private String renameFunction(String incString)
  {
     return incString + "blub";
  }
}

public class B extends A {
  private String bar;

  @Override
   private void methodA() {
     String foo = "bla";
     foo = renameFunction(foo); //will not work as it's private
     this.bar = foo;
  }
}
  • use reflection perhaps? – Shark Jul 12 '19 at 14:23
  • 1
    [Relevant question](https://stackoverflow.com/questions/880365/any-way-to-invoke-a-private-method) here's a link to the similar question you're asking. – Shark Jul 12 '19 at 14:24
  • Your question is full of wrong terms or concepts. There is no “public variable” in class `A`; the variable `foo` within `methodA` is a *local variable*. Further, there is no “nested private method”, as there is no nesting. There’s just a private method and you are trying to invoke it from the subclass’ method, because you are trying to retrace what the superclass method does, which has nothing to do with attempting to access the local variable. – Holger Jul 15 '19 at 13:37

1 Answers1

2

No. Since foo is a variable inside a method, it's not even field on A, therefor it lives only in the scope of doSomthing's execution and not accessible from outside (not from B or from A for that matter).

invoking the private method is possible only with reflection, which is not something recommended unless you want it in a unit test or something like that

Nir Levy
  • 12,750
  • 3
  • 21
  • 38