特征是否可以在Scala中使用其方法使用的私有成员?如果有人想在Java中使用它会有问题吗?

时间:2014-10-03 05:06:36

标签: scala jvm

由于trait中的方法在JVM抽象类中转换为静态方法,它是否能够引用私有字段?

1 个答案:

答案 0 :(得分:1)

检查如何放宽访问权限:

scala> trait T { private val t: Int = 42 ; def value = t }
defined trait T

scala> :javap -prv T
Binary file T contains $line3.$read$$iw$$iw$T
[snip]
{
  public abstract void $line3$$read$$iw$$iw$T$_setter_$$line3$$read$$iw$$iw$T$$t_$eq(int);
    flags: ACC_PUBLIC, ACC_ABSTRACT

  public abstract int $line3$$read$$iw$$iw$T$$t();
    flags: ACC_PUBLIC, ACC_ABSTRACT

  public abstract int value();
    flags: ACC_PUBLIC, ACC_ABSTRACT
}

scala> :javap -prv T$class
Binary file T$class contains $line3.$read$$iw$$iw$T$class
[snip]
{
  public static int value($line3.$read$$iw$$iw$T);
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=1, locals=1, args_size=1
         0: aload_0       
         1: invokeinterface #13,  1           // InterfaceMethod $line3/$read$$iw$$iw$T.$line3$$read$$iw$$iw$T$$t:()I
         6: ireturn       
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
               0       7     0 $this   L$line3/$read$$iw$$iw$T;
      LineNumberTable:
        line 7: 0

  public static void $init$($line3.$read$$iw$$iw$T);
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=2, locals=1, args_size=1
         0: aload_0       
         1: bipush        42
         3: invokeinterface #21,  2           // InterfaceMethod $line3/$read$$iw$$iw$T.$line3$$read$$iw$$iw$T$_setter_$$line3$$read$$iw$$iw$T$$t_$eq:(I)V
         8: return        
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
               0       9     0 $this   L$line3/$read$$iw$$iw$T;
      LineNumberTable:
        line 7: 0
}