如何使用反射获取默认构造函数参数?

How to get default constructor parameter using reflection?

这种看似容易理解,现在一头雾水:

scala> class B(i:Int)
defined class B

scala> classOf[B].getDeclaredFields
res12: Array[java.lang.reflect.Field] = Array()

请注意:

scala> class C(i:Int){
     | val j = 3
     | val k = -1
     | }
defined class C

scala> classOf[C].getDeclaredFields
res15: Array[java.lang.reflect.Field] = Array(private final int C.j, private final int C.k)

如果您将 i 声明为 valvar,或者如果您将 B 设为 class,那么您将看到:

scala> classOf[B].getDeclaredFields
res1: Array[java.lang.reflect.Field] = Array(private final int B.i)

如果两者都不做,则不会生成名为 i 的方法或字段,因为它只是一个从未使用过的构造函数参数;没有理由它会导致方法或字段存在。

请注意,Scala 编译器从不生成 public 成员,只会生成私有成员。来自外部的访问意味着通过名为 i.

方法