简体   繁体   中英

Invoke an overridden instance method using reflection in java

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

  • have it done in java
  • and when @Override has not been specified on the child method (this is for when I don't have access to the source)

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?

MethodHandles can be used to invoke a superclass method:

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM