如何从包含父类的hashMap获取子类属性作为Java中的entryset?

时间:2016-02-11 15:37:18

标签: 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
}

如上所示代码我无法访问childAttribute,因为我从HashMap获取父类型对象。如何创建包含父类型和子类型对象并到达子对象属性的HashMap?

1 个答案:

答案 0 :(得分:1)

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

投射到正确的类型可以解决问题。感谢@Miguel Gamboa和@nolexa。