scala 保护修饰符转换为 java 类是 public [英] scala protected modifier convert to java class is public
问题描述
在scala类中,我定义了一个受保护的字段和一个受保护的方法:
In a scala class, I have defined a protected field and a protected method:
TestProtected.scala:
TestProtected.scala:
class TestProtected {
protected var f = 0
protected def m = 1
}
在我看来,它会将受保护的 f 和 m 转换为 Java 受保护的文件和方法.但是当我使用jd-gui将TestProtected.class反编译为java文件时,结果出乎我的意料:
In my opinion, it will convert the protected f and m to a java protected filed and method. But when i use jd-gui to decompiler the TestProtected.class to java file, the result was beyond my expectation:
@ScalaSignature(bytes="...")
public class TestProtected
{
private int f= 0;
public int f() { return this.f; }
public void f$eq(int x$1) { this.f = x$1; }
public int m() {
return 1;
}
}
java 文件中的 f 和 m 是公共的吗?
The f and m in java file is public?
为什么?
谢谢!
推荐答案
首先,Scala protected
不同于 Java protected代码>:
Firstly, Scala protected
is different from Java protected
:
Java 的protected
对同一个包 和子类、Scala 可见> protect
只对子类可见,所以Scala的protected
比Java 的.
Java's protected
is visible to same package and subclass, Scala protect
is only visible to subclass, so Scala's protected
is more restrictive than Java's.
所以这是由JVM Level
访问修饰符与Scala访问修饰符不同引起的,我们知道Scala在JVM上运行
,为了在JVM
上运行,需要在JVM
中生成兼容的字节码.
So this is caused by JVM Level
access modifier is not same as Scala access modifier, we know Scala runs on JVM
, for running on JVM
, it needs to generate the compatible byte code in JVM
.
还有一些其他的例子,比如:
There are some other example like:
private
private[this]
private[package]
有一些关于 Scala Access 的参考:
There are some reference about Scala Access:
这篇关于scala 保护修饰符转换为 java 类是 public的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!