[英]Scala reflection: Why does getMethods return private vals defined in superclass?
Code below defines a trait T
with a private val someVal
and an anonymous class extending T
. 下面的代码定义了一个特征
T
,它具有私有val someVal
和一个扩展T
的匿名类。 If we call getMethods
from the instance of the anonymous class, someVal
is listed as a public method: 如果我们从匿名类的实例调用
getMethods
, someVal
被列为公共方法:
scala> trait T { private val someVal = 3 }
defined trait T
scala> new T {}.getClass.getMethods.apply(0)
res2: java.lang.reflect.Method = public int $anon$1.$line6$$read$T$$someVal()
Of course someVal
isn't accessible in this subclass, but why is it even in the return of getMethods
, as public? 当然
someVal
在这个子类中是不可访问的,但为什么它甚至在getMethods
的返回中,作为公共?
trait
s compile to interfaces
, because they need multiple-inheritance. trait
s编译为interfaces
,因为它们需要多重继承。 But interfaces can have neither fields nor non- public
members. 但是接口既没有字段也没有非
public
成员。 Therefore, a field becomes a pair of public
accessors, mangled by the trait's name, and the compiler is tasked with placing the field into all subclasses and implementing the accessors. 因此,字段成为一对
public
访问器,由特征名称破坏,编译器的任务是将字段放入所有子类并实现访问器。 Any methods on T
trying to access someVal
go through the getter, and the static
$init$
function, which contains the constructor code, uses the setter to set it to 3
. T
试图访问someVal
任何方法都通过getter,而包含构造函数代码的static
$init$
函数使用setter将其设置为3
。 If your val
were declared public
, then the name of the getter would be demangled to just someVal
, and external code would use that, and if it were also var
, the setter would demangle to someVal_=
, which subsequently mangles to someVal_$eq
. 如果你的
val
被声明为public
,那么getter的名称将被someVal
为someVal
,而外部代码将使用它,如果它也是var
,则setter将someVal_=
为someVal_=
,随后将someVal_$eq
。 The horribly long mangled names are pretty much enough to keep anyone from using them, anyway, and it's only relevant when doing Java interop. 无论如何,可怕的长名称非常足以阻止任何人使用它们,并且只有在进行Java互操作时它才有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.