0

我有一个场景,其中我有以下 xml 和类

XML:

<packages>
<package>
<name>class1</name>
      <classes>300</classes>
      <functions>21</functions>
      <ncss>283</ncss>
      <javadocs>20</javadocs>
      <javadoc_lines>111</javadoc_lines>
      <single_comment_lines>11</single_comment_lines>
      <multi_comment_lines>221</multi_comment_lines>
</package>
</packages>

Java 类:

Class Package {

//all variables and setters getters
}

class Packages {
public  ArrayList<Package> x;
//add and remove methods for x
}

在 mainClass 我有:

    BufferedReader br = new BufferedReader(new FileReader(new                                                    
File("C:\\old_code_complexity.xml")));
    String line;
    StringBuilder sb = new StringBuilder();

    while((line=br.readLine())!= null){
        sb.append(line.trim());
    }

    String x = sb.toString();

    XStream xstream = new XStream();
    xstream.alias("package", Package.class);
    xstream.alias("packages", Packages.class);
    xstream.addImplicitCollection(Packages.class, "x");



    Packages pList = (Packages)xstream.fromXML(x);
    Package pack = (Package) xstream.fromXML(x);

    System.out.println(xstream.toXML(pack));

println 之前的行每次都会出错

Exception in thread "main" java.lang.ClassCastException: dummyCompare.input.Packages     cannot be cast to dummyCompare.input.Package
    at dummyCompare.Logic.mainClass.main(mainClass.java:41)

如何管理此强制转换操作,以便可以检索可以在代码中操作的对象数组?

4

1 回答 1

0

你为什么要把你的对象投射Packages到一个Package对象上?只需创建一个吸气Packages

public  ArrayList<Package> getPackageList() {
  return x;
}

而不是铸造它:

Packages pList = (Packages)xstream.fromXML(x);
ArrayList<Package> pack = pList.getPackageList();
于 2013-04-10T07:36:07.483 回答