mardi 31 octobre 2017

Scala reflection. Get private field in trait

I am trying to use private trait field in testing. Very simple example:

//Works fine with class A, but not trait A
trait A {  
  private val foo = "Some string"
}

class Test extends A {
  val field = classOf[A].getDeclaredField("foo")
  field.setAccessible(true)
  val str = field.get(this).asInstanceOf[String]
}

I got:

java.lang.NoSuchFieldException: foo at java.lang.Class.getDeclaredField

live example here

How to get this snippet executable?





Aucun commentaire:

Enregistrer un commentaire