日期:2014-05-20  浏览次数:20883 次

这样的向下转型怎么不报运行时异常ClassCastException
在网上看到个XML列子程序,程序是可以运行的,这是程序中的一个方法片段
我的问题写在了下面程序的注释部分。第二个程序就是一个向下转型的列子,但是却报错了。
Java code

class OutContent {
    int m = 0;

    public void output(NodeList nodeList) {
        int size = nodeList.getLength();
        for (int k = 0; k < size; k++) {
            Node node = nodeList.item(k);
            if (node.getNodeType() == Node.TEXT_NODE) {
                                //父类型Node强转成子类型Text,怎么不报错?
                Text textNode = (Text) node;
                String content = textNode.getWholeText();
                m++;
                System.out.print(content);
            }
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                                //这里也是样的问题
                Element elementNode = (Element) node;
                String name = elementNode.getNodeName();
                System.out.print(name);
                NodeList nodes = elementNode.getChildNodes();
                output(nodes);
            }
        }
    }


Java code

package com.test;

class A {

    void aMthod() {

        System.out.println("A method");

    }

}

class B extends A {

    void bMethod1() {

        System.out.println("B method 1");

    }

    void bMethod2() {

        System.out.println("B method 2");

    }

}

public class C {

    public static void main(String[] args) {
        A a2 = new A();

        B b2 = (B) a2; // 向下转型,编译无错误,运行时将出错

        b2.aMthod();

        b2.bMethod1();

        b2.bMethod2();

    }

}



------解决方案--------------------
Map get() { return new HashMap();}

(HashMap)get();

类似这种情况