不能使用 getDeclaredFields() 来检索 Scala 类的字段 [英] Cannot use getDeclaredFields() to retrieve fields of a Scala class
问题描述
我正在尝试将 Java 库 (JOhm) 与 Scala 一起使用,并注意到当 lib 尝试使用诸如 model.getClass().getDeclaredFields()之类的东西读取我的 Scala 类的字段时它失败代码>.
I'm trying to use a Java library (JOhm) with Scala and noticed it fails when the lib tries to read the fields of my Scala classes with something like model.getClass().getDeclaredFields()
.
然后我决定尝试用 Scala 解释器中的简单示例做同样的事情:
Then I decided to try to do the same with simple examples in 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()
确实,我们根本没有任何字段.
Indeed, we get no field at all.
现在,如果我试试这个会怎样:
Now, what if I try this:
scala> class myClass2(attribute1: String, attribute2: String, attribute3: String) { override def toString = this.attribute1 }
defined class myClass2
scala> val myInstance2 = new myClass2("value1", "value2", "value3")
myInstance2: myClass2 = value1
scala> myInstance2.getClass().getDeclaredFields()
res1: Array[java.lang.reflect.Field] = Array(private final java.lang.String myClass2.attribute1)
因此,如果使用类方法之一中的字段之一,则可以通过 getDeclaredFields() 找到它.我在这里错过了什么?
So if use one of the fields in one of the class' methods, it is found by getDeclaredFields(). What am I missing here?
推荐答案
您缺少的是构造函数参数不会自动提升到字段.
相反,它们只有在被使用时才会被提升.你使用了 attribute1
所以它变成了一个字段;你没有使用其他人,所以他们没有.
Rather, they are promoted only if they are used. You used attribute1
so it was turned into a field; you didn't use the others so they were not.
如果你将它们声明为 val
或 var
,或者类是一个 case 类,它们也会被提升为字段(因为它们实际上会生成访问器方法,因此被使用).
If you declare them as val
or var
, or the class is a case class, they will also be promoted to fields (since they will actually have accessor methods generated, and thus are used).
这篇关于不能使用 getDeclaredFields() 来检索 Scala 类的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!