Java – you cannot use getdeclaraedfields() to retrieve fields from Scala classes
I'm trying to use Scala's Java library (johm) and notice that when lib tries to use something like model getClass(). Getdeclaraedfields() will fail when it reads the fields of my Scala class
Then I decided to try a simple example from the scala interpreter:
scala> import java.lang.reflect.Field; import java.lang.reflect.Field scala> class myClass(attribute1: String,attribute2: String,attribute3: String) defined class myClass scala> val myInstance = new myClass("value1","value2","value3") myInstance: myClass = myClass@7055c39a scala> myInstance.getClass().getDeclaredFields() res0: Array[java.lang.reflect.Field] = Array()
In fact, we have no field at all
Now, what if I try this:
scala> class myClass2(attribute1: String,attribute3: String) { override def toString = this.attribute1 } defined class myClass2 scala> val myInstance2 = new myClass2("value1","value3") myInstance2: myClass2 = value1 scala> myInstance2.getClass().getDeclaredFields() res1: Array[java.lang.reflect.Field] = Array(private final java.lang.String myClass2.attribute1)
Therefore, if you use a field in one of the class' methods, you can find it through getdeclaraedfields() What did I miss here?
Solution
What you are missing is that constructor parameters are not automatically promoted to fields
Instead, they are promoted only when used You use attribute1, so it becomes a field; You didn't use other people, so they didn't
If they are declared as Val or VaR, or if the class is a case class, they will also be promoted to fields (because they actually generate accessor methods, so they are used)