Edit special thanks to @Seth Tisue (up votes and accept to him please)
class Test extends A {
val field:Field = this.getClass.getDeclaredField("A$$foo")
field.setAccessible(true)
println(field.get(this).asInstanceOf[String])
}
"A$$foo" is the correct way to get the super type attribute, this and use this.getClass
.
I didn't know it before, but with that correction, your code will work just great!
First Idea:
trait A {
private val foo = "Some string"
}
class Test extends A {
val fields: Seq[Field] = this.getClass.getDeclaredFields.toList
val field = fields.filter(x => {
println(x.getName)
x.getName.contains("foo")
}).head
field.setAccessible(true)
println(field.get(this).asInstanceOf[String])
}
As you can see, when you print the name of the "foo" variable, is not really "foo", it's something else:
A$A295$A$A295$A$$foo
in my case, and that's why you (and I) got the error
java.lang.NoSuchFieldException: foo at java.lang.Class.getDeclaredField
So, my idea for now, I hope someone came with a better one, is look if "foo" is inside the variable name "A$A295$A$A295$A$$foo" so you can tell thats the variable you where looking for.