2014-11-06 3 views
0

내 코드가 실행되는 동안 ClassCastException으로 실패합니다. 디버깅을 시도했지만 헛된. 필자는 필드가있는 클래스 제목을 선언했으며 해당 클래스의 개체를 목록에로드하려고합니다. 아래는 코드입니다. 그것은 라인에서 실패합니다 : List items = (List)(it.next()). 제네릭에 ?을 추가해도 도움이되지 않습니다. List 선언에 언급 된 제네릭은 없지만 객체가 캐스트 된 것 같습니다. 내가 누락 된 기본 개념이 있습니까?목록을 반복 할 때 Java ClassCastException이 throw됩니다.

아래의 방법에서 데이터를 XML 파일로 인코딩하려고합니다.

private void encodeSection(PrintStream output, Indenter indenter, 
            String name, List list) { 
      String indent = indenter.makeString(); 

      output.println(indent + "<" + name + "s>"); 

      indenter.in(); 
      String indentNext = indenter.makeString(); 

      if (list == null) { 
       // the match is any 
       output.println(indentNext + "<Any" + name + "/>"); 
      } else { 
       String nextIndent = indenter.makeString(); 

       Iterator it = list.iterator(); 
       indenter.in(); 

       while (it.hasNext()) { 
        List items = (List)(it.next());//-------------> Error occurs 
        output.println(indentNext + "<" + name + ">"); 

        Iterator matchIterator = items.iterator(); 
        while (matchIterator.hasNext()) { 
         TargetMatch tm = (TargetMatch)(matchIterator.next()); 
         tm.encode(output, indenter); 
        } 

        output.println(indentNext + "</" + name + ">"); 
       } 

       indenter.out(); 
      } 

      indenter.out(); 
      output.println(indent + "</" + name + "s>"); 
     } 

    } 

스택 추적은 다음이 List 당신이 이상 반복하는 것이합니다 (List 인터페이스를 구현하는 클래스의 즉, 인스턴스) 단지 형 List의 요소가 포함되어있는 경우

Exception in thread "main" java.lang.ClassCastException: SubjectID_V cannot be cast to java.util.List 
    at Target_V.encodeSection(Target_V.java:71) 
    at Target_V.encode(Target_V.java:41) 
at com.sun.xacml.AbstractPolicy.encodeCommonElements(Unknown Source) 
    at com.sun.xacml.PolicySet.encode(Unknown Source) 
    at PolicyFactory_V.main(PolicyFactory_V.java:56) 
+0

전체 코드를 게시하지 않았습니다. 또한 한 가지 유형의 콜렉션을 다른 유형으로 캐스팅하려고 시도하기 때문에 에로스가 발생할 확률이 높습니다. 아마도 허용되지 않습니다. 당신의'SubjectID_V'의 타입은 무엇입니까? – ha9u63ar

+0

여기에 '원시 타입'을 많이 사용하고 있습니다. 제네릭 타입이 무엇인지 그리고'List'와'Iterator'에서 어떻게 사용하는지보세요. – Tom

답변

2

List items = (List)(it.next())에만 작동합니다.

오류를 기반으로 SubjectID_V 유형의 인스턴스를 List으로 전송하려고합니다. 해당 목록을 초기화하는 코드를 살펴 봐야합니다. 거기에 오류가있을 수 있습니다.

일반 목록을 사용하면 코드가 컴파일을 처음부터 통과하지 못하게되므로이 예외가 발생하지 않도록 도움이 될 수 있습니다.

+0

답장을 보내 주셔서 감사합니다! – Lucky