[英]Access scala class fields in java
I have defined the class A
in Scala:我在 Scala 中定义了A
类:
class A(var number: Int)
But when I try to access its member field number
in java, I get an error:但是当我尝试在 java 中访问其成员字段number
时,出现错误:
A a = new A();
a.number = 4;
Results in: java: number has private access in A
.结果: java: number has private access in A
。 If I try to access the number
from scala, there is no problem.如果我尝试从 Scala 访问该number
,则没有问题。
What can I do to get around this issue?我该怎么做才能解决这个问题?
Use getter使用吸气剂
a.number();
and setter和二传手
a.number_$eq(4);
instead of the field itself a.number
.而不是字段本身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.如果我尝试从 Scala 访问该number
,则没有问题。
In Scala when you write a.number
or a.number = 4
you actually call getter/setter (this is syntax sugar).在 Scala 中,当您编写a.number
或a.number = 4
您实际上调用了 getter/setter(这是语法糖)。
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
时查看生成的类文件,这可以从 Dmytro 的回答中解释 getter number()
和 setter 方法number_$eq
// 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.