mercredi 23 août 2017

Non-virtual method invocation using reflection

In Java, when working with java.lang.reflect.Method how can I invoke a function without it being a virtual call?

I.e. I want this code to print "good" instead of what it currently does, which is print "bad":

Foo.java:

public class Foo {
  public void doit() {
    System.out.println("good");
  }
}

Bar.java:

import java.lang.reflect.Method;

public class Bar extends Foo {
  public void doit() {
    System.out.println("bad");
  }

  public static void main(String[] args) throws Exception {
    Bar b = new Bar();
    /* Using Foo.class ought to do it right? */
    Method m = Foo.class.getDeclaredMethod("doit", new Class[]{});
    /* Surely if that didn't do it casting to Foo would? */
    m.invoke((Foo)b, new Object[]{});
  }
}

Nothing I do using reflection succeeds in printing "good".

My expectation was that using one or more of casting the first argument of invoke to Foo, and/or using Foo.class.getDeclaredMethod instead of Bar.class would be sufficient. Clearly I'm wrong about that, how can I get the desired behaviour still using reflection?





Aucun commentaire:

Enregistrer un commentaire