Reputation: 1
i am writing a function that should get the names of all field name in a class but can you really access private fields in Scala? I thought it should be possible, but they are not showing at all and i dont understand why ?
for example:
class Cat(isBlackC: Boolean){
private val isBlack: Boolean = isBlackC
}
val cat = new Cat(true)
for(field <- cat.getClass.getDeclaredFields){
field.setAccessible(true)
println(field.get(cat))
}
and the output is nothing :(
Upvotes: 0
Views: 39
Reputation: 121
Scala translates private fields into private methods or uses name mangling to make the fields harder to access directly. For example, the isBlack
field might be renamed to something like isBlack$1
You can use Java reflection to access private fields, but you'll need to consider how Scala compiles them.
import scala.reflect.runtime.universe._
class Cat(isBlackC: Boolean) {
private val isBlack: Boolean = isBlackC
}
val cat = new Cat(true)
// Use Java Reflection
val fields = cat.getClass.getDeclaredFields
fields.foreach { field =>
field.setAccessible(true) // Allow access to private fields
println(s"${field.getName}: ${field.get(cat)}")
}
Upvotes: 2