0

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?

Community
  • 1
  • 1
zcaudate
  • 13,998
  • 7
  • 64
  • 124
  • 4
    Cool. Start writing some code. And if you have a question, come back here. @Overriden is irrelevant to the problem, BTW. – JB Nizet Feb 06 '14 at 22:52
  • You've got a problem @zcaudate. The `@Override` annotation is an annotation that does not appear in the compiled bytecode. It is a compile time language feature. – Martijn Courteaux Feb 06 '14 at 23:03

2 Answers2

2

MethodHandles can be used to invoke a superclass method:

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

zcaudate
  • 13,998
  • 7
  • 64
  • 124
1

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/