访问 Scala 类中的字段在 Java 中。

huangapple go评论78阅读模式
英文:

Access scala class fields in java

问题

我已经在Scala中定义了类A

class A(var number: Int)

但是当我尝试在Java中访问它的成员字段number时,出现错误:

A a = new A();
a.number = 4;

导致:java: number在A中具有私有访问权限
如果我尝试从Scala访问number,就没有问题。

我该怎么解决这个问题?

英文:

I have defined the class A in Scala:

class A(var number: Int)

But when I try to access its member field number in java, I get an error:

A a = new A();
a.number = 4;

Results in: java: number has private access in A.
If I try to access the number from scala, there is no problem.

What can I do to get around this issue?

答案1

得分: 9

使用getter方法:

a.number();

和setter方法:

a.number_$eq(4);

而不是直接使用字段本身 a.number

或者使用:

a.getNumber();
a.setNumber(4);

如果你对字段进行了注解:

import scala.beans.BeanProperty

class A(@BeanProperty var number: Int)

> 当我尝试从Scala访问 number 时,没有问题。

在Scala中,当你写 a.numbera.number = 4 时,实际上调用的是getter和setter方法(这是语法糖)。

英文:

Use getter

a.number();

and setter

a.number_$eq(4);

instead of the field itself a.number.

Or

a.getNumber();
a.setNumber(4);

if you annotate the field

import scala.beans.BeanProperty

class A(@BeanProperty var number: Int)

> If I try to access the number from scala, there is no problem.

In Scala when you write a.number or a.number = 4 you actually call getter/setter (this is syntax sugar).

答案2

得分: 3

你可以在编译A.scala时查看生成的类文件,这可以解释Dmytro的回答中的getter方法number()和setter方法number_$eq

// A.scala
class A(var number: Int)
> scalac A.scala
> javap -p A.class
// 上述步骤的输出

public class A {
  private int number;
  public int number();
  public void number_$eq(int);
  public A(int);
}
英文:

You can look at the generated class file when you compile A.scala, that can explain getter number() and setter method number_$eq from Dmytro's answer

// A.scala
class A(var number: Int)
> scalac A.scala
> javap -p A.class
// output of above step

public class A {
  private int number;
  public int number();
  public void number_$eq(int);
  public A(int);
}

huangapple
  • 本文由 发表于 2020年9月2日 19:16:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63704358.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定