zcaudate
zcaudate

Reputation: 14258

Invoke an overridden instance method using reflection in java

I would like to do this: Use reflection to invoke an overridden base method but

I have:


package test;

public class A{
  public String toString(){
    return "A";
  }
}

package test;

public class B extends A{
  public String toString(){
    return "B";
  }
}

I want ((A)(new B())).toString() to be "A", not "B". Is there a way to get this using reflection?

Upvotes: 0

Views: 304

Answers (2)

zcaudate
zcaudate

Reputation: 14258

MethodHandles can be used to invoke a superclass method:

https://www.baeldung.com/java-method-handles

Upvotes: 2

Tommy Brettschneider
Tommy Brettschneider

Reputation: 1500

Your challenge (I want ((A)(new B())).toString() to be "A", not "B".) has nothing to do with reflection at all. even if you execute ((A)(new B())).toString() in your java program without reflection, it will always print "B". Reason for this is that both classes A and B override the toString() method, at runtime the real object type will be determined and the toString() method of that type/class will be called. So in your example: you create an instance of B, so real object type is B! then you upcast to A, so reference type will be A now, but the referenced, "real" object type will remain B!

https://www.programcreek.com/2009/02/overriding-and-overloading-in-java-with-examples/

Upvotes: 1

Related Questions