Scala 获取参数的类

发布于 2024-11-04 00:26:28 字数 733 浏览 0 评论 0原文

因此,在 Java 中,我有一个包含 HashMap 的类,该类使用该类作为指向同一类的对象的键。

class ComponentContainer {
  private HashMap<Class<? extends Component>, Component> componentMap

  public ComponentContainer {
    componentMap = new HashMap<Class<? extends Component>, Component>();
  }

  public void set (Component c) {
    componentMap.put(c.getClass(), c);
  }
}

然而,当我尝试在 Scala 中的特征中执行相同的操作时,我发现自己收到类型不匹配错误,即在需要 Class[Component] 的位置找到了 java.lang.Class[?0]。

trait ComponentContainer {
  val componentMap: HashMap[Class[Component], Component] = HashMap.empty

  def set (c: Component) {
    val t = (c.getClass, c)
    componentMap += t
  }    
}

这让我绝对难住任何帮助将不胜感激。

So in Java I had a class that contained a HashMap that used the class as a key pointing to an object of the same class.

class ComponentContainer {
  private HashMap<Class<? extends Component>, Component> componentMap

  public ComponentContainer {
    componentMap = new HashMap<Class<? extends Component>, Component>();
  }

  public void set (Component c) {
    componentMap.put(c.getClass(), c);
  }
}

However when I try to do the same thing in Scala within a trait I find myself getting a type mismatch error that a java.lang.Class[?0] was found where Class[Component] was needed.

trait ComponentContainer {
  val componentMap: HashMap[Class[Component], Component] = HashMap.empty

  def set (c: Component) {
    val t = (c.getClass, c)
    componentMap += t
  }    
}

This has me absolutely stumped any help would be appreciated greatly.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

遗弃M 2024-11-11 00:26:28

您的代码无法编译的原因是 T.getClass 方法的结果是 Class[_] 而不是 Class[T]。 VonC 此处。

从您的源代码中,我看不到您是否关心类实例的类型参数,但以下版本的代码可以编译:

trait ComponentContainer {
  val componentMap: HashMap[Class[_], Component] = HashMap.empty

  def set (c: Component) {
    val t = (c.getClass, c)
    componentMap += t
  }
}

The reason your code doesn't compile is that T.getClass method has result Class[_] and not Class[T]. Details of getClass has been explained by VonC here.

From your source code I cannot see if you care about type parameter of Class instances but following version of your code compiles:

trait ComponentContainer {
  val componentMap: HashMap[Class[_], Component] = HashMap.empty

  def set (c: Component) {
    val t = (c.getClass, c)
    componentMap += t
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文