在Java中使用Scala常数 [英] Use Scala constants in Java

查看:150
本文介绍了在Java中使用Scala常数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在为未来的项目评估Scala,遇到了一些奇怪的事情.我在JSP中为我们创建了以下常量:

I am currently evaluating Scala for future projects and came across something strange. I created the following constant for us in a JSP:

val FORMATED_TIME = "formatedTime";

它没有用.经过一些实验后,我决定进行反编译以了解其底部:

And it did not work. After some experimenting I decided to decompile to get to the bottom of it:

private final java.lang.String FORMATED_TIME;

public java.lang.String FORMATED_TIME();
  Code:
   0:   aload_0
   1:   getfield    #25; //Field FORMATED_TIME:Ljava/lang/String;
   4:   areturn

现在,这很有趣!就我个人而言,我已经想了好一阵子了,为什么Java中的检查员为什么需要前缀 get 和变量mutator前缀 set ,因为它们位于不同的命名空间中.

Now that is interesting! Personally I have been wondering for quite a while why an inspector needs the prefix get and a mutator the prefix set in Java as they live in different name-spaces.

但是,向团队其他成员解释这一点仍然很尴尬.那么有没有检查员的公共常量是可能的吗?

However it might still be awkward to explain that to the rest of the team. So is it possible to have a public constant without the inspector?

推荐答案

这是因为

This is because of the Uniform Access Principle, i.e.: Methods and Fields Are Indistinguishable

请参见此答案

在Scala 2.8.0中,这意味着您有 一个同伴对象,你会失去你的 静态转发器)

In Scala 2.8.0 this means if you have a companion object, you lose your static forwarders)

如果您在Scala中拥有此功能,

If you have this in Scala:

//Scala
object CommonControler {
      val FORMATED_TIME = "formatedTime";
}

您可以在Java中像这样使用它

You may use it like this from Java

//Java

// Variables become methods
CommonControler$.MODULE$.FORMATED_TIME();
// A static forwarder is avaliable
CommonControler.FORMATED_TIME();

另请参阅《 深度缩放》

还要注意 @ scala.reflect.BeanProperty 上课.

这篇关于在Java中使用Scala常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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