繁体   English   中英

如何在Java中从包含父类作为条目集的hashMap中获取子类属性?

[英]How can I get child class attributes from a hashMap containing parent class as entryset in Java?

public class SuperVertex extends Vertex{
    int childAttr = 1;
}

public class Vertex {
   int name = 0;
}

public class Test {
    SuperVertex sv = new SuperVertex();
    Vertex v = new Vertex();
    HashMap<Vertex, Vertex> hmp = new HashMap<Vertex, Vertex>();
    hmp.put(v,v);
    hmp.put(sv,sv);
    hmp.get(v).name //works
    hmp.get(sv).name //works
    hmp.get(sv).childAttr //doesn't work
}

如上面的代码所示,由于我从HashMap获得了父类型对象,因此我无法访问childAttribute。 如何创建同时包含父类型和子类型对象的HashMap并到达子对象属性?

(SuperVertex)hmp.get(sv).childAttr//works

强制转换为正确的类型可以解决此问题。 感谢@Miguel Gamboa和@nolexa。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM