jeudi 27 octobre 2016

How to call an overriden method using reflection?

Consider we have the following:

 class Base { def name = "Base" }
 class Successor extends Base {
    override def name = "Successor"
 }

I have tried to do the following (took from How to call a superclass method using Java reflection):

import java.lang.invoke.{MethodHandles, MethodHandle, MethodType}

object TestApp {
    def main(args: Array[String]) {
        val a = new Successor;
        val h1 = MethodHandles.lookup().findSpecial(classOf[Base],
                                                    "name",
                                                    MethodType.methodType(classOf[String]),
                                                    classOf[Successor]);
        println(h1.invoke(a));
    }
}

but I get a runtime exception:

java.lang.IllegalAccessException: no private access for invokespecial: class Successor, from TestApp$

I was told that it is possible that Java reflection may not work correctly for Scala. Is it true? Or I simply do something wrong?





Aucun commentaire:

Enregistrer un commentaire