scala 保护修饰符转换为 java 类是 public [英] scala protected modifier convert to java class is public

查看:34
本文介绍了scala 保护修饰符转换为 java 类是 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:

Javaprotected同一个包子类Scala 可见> protect 只对子类可见,所以ScalaprotectedJava 的.

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访问修饰符不同引起的,我们知道ScalaJVM上运行,为了在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 中变为公开

Scala 访问

受保护成员

这篇关于scala 保护修饰符转换为 java 类是 public的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆