我可以从 Java 访问不带括号的 Scala 对象的 val 吗?
给定以下 Scala 对象:
object ScalaObject {
val NAME = "Name"
}
Scala 编译器似乎生成了一个无参数方法来访问 NAME
字段。但是,当我尝试从 Java 访问该字段时,访问该字段的唯一方法似乎是作为无参数方法,例如:
System.out.println(ScalaObject$.MODULE$.NAME());
有没有办法诱使 Scala 编译器允许 Java 访问 val code> 按照预期的 Java 习惯用法为:
System.out.println(ScalaObject$.MODULE$.NAME);
Given the following Scala object:
object ScalaObject {
val NAME = "Name"
}
It appears that the Scala compiler generates a parameterless method to access the NAME
field. However, when I try to access this field from Java, it looks like the only way to access this field is as a parameterless method like:
System.out.println(ScalaObject$.MODULE$.NAME());
Is there a way to coax the Scala compiler to allow Java to access the val
per the expected Java idiom as:
System.out.println(ScalaObject$.MODULE$.NAME);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
严格来说,答案是否定的,因为 scala 不仅仅生成一个字段,而是生成一对访问它的方法。但是,使用
@scala.reflect.BeanProperty
注解 scalaval
将生成 Java 风格的 getter 和 setter 方法。所以虽然你不能说(在你的情况下)
你将能够说
这是一种更像Java的习惯用法,但不是你所希望的。
注意,我还没有尝试使用像这样的全大写名称的
@BeanProperty
,所以我不确定它实际上会产生什么。Strictly, the answer is no, because scala isn't generating just a field, but a pair of methods for accessing it. However, annotating the scala
val
with@scala.reflect.BeanProperty
will produce Java-style getter and setter methods.so while you wouldn't be able to say (in your case)
You would be able to say
Which would be a more Java-like idiom, just not the one you were hoping for.
N.B. I haven't tried
@BeanProperty
with an all-uppercase name like that, so I'm not sure what it would actually produce.不,因为在字节码中有不同的指令来访问字段和调用方法。然后您必须修补 Javac(以及您的 IDE 语法荧光笔)。
No, because in bytecode there are different instruction to access field and invoke method. You must patch Javac then (and your IDE syntax highlighter).