Scala 获取参数的类
因此,在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码无法编译的原因是
T.getClass
方法的结果是Class[_]
而不是Class[T]
。 VonC 此处。从您的源代码中,我看不到您是否关心类实例的类型参数,但以下版本的代码可以编译:
The reason your code doesn't compile is that
T.getClass
method has resultClass[_]
and notClass[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: