在scala中访问java基类的静态成员 [英] access java base class's static member in scala

查看:240
本文介绍了在scala中访问java基类的静态成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些用Java编写的代码。对于新课程,我打算用Scala编写。我有一个关于访问基类的受保护的静态成员的问题。以下是示例代码:

Ihave some codes written in Java. And for new classes I plan to write in Scala. I have a problem regarding accessing the protected static member of the base class. Here is the sample code:

Java代码:

class Base{
    protected static int count = 20;
}

scala代码:

class Derived extends Base{
    println(count);
}

对此有何建议?如何在不修改现有基类的情况下解决这个问题

Any suggestion on this? How could I solve this without modifying the existing base class

推荐答案

这在Scala中是不可能的。由于Scala没有 static 的表示法,因此无法访问父类的 protected static 成员。这是已知限制

This isn't possible in Scala. Since Scala has no notation of static you can't access protected static members of a parent class. This is a known limitation.

解决方法是执行以下操作:

The work-around is to do something like this:

// Java
public class BaseStatic extends Base {
  protected int getCount() { return Base.count; }
  protected void setCount(int c) { Base.count = c; }
}

现在你可以从这个新类继承并通过以下方式访问静态成员getter / setter方法:

Now you can inherit from this new class instead and access the static member through the getter/setter methods:

// Scala
class Derived extends BaseStatic {
  println(getCount());
}

这很难看 - 但如果你真的想用保护静态成员那就是你必须要做的事情。

It's ugly—but if you really want to use protected static members then that's what you'll have to do.

这篇关于在scala中访问java基类的静态成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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