문제

I am getting following error while trying to execute following code snippets. Please let me know what are the possible reasons of getting this error.

List list = .... ;
for(Object obj:list)
{
Object[] myObj = (Object[])obj;
Long lg = ...;
if(myObj[1]!=null){
lg = ((BigDecimal)myObj[1]).longValue();
}



java.lang.ClassCastException
     at java.lang.Class.cast(Class.java:...)
도움이 되었습니까?

해결책

The reason is that obj is not an array or that myObj[1] is not a BigDecimal.

To debug this, you can add these lines:

System.out.println(obj.getClass());
System.out.println(myObj[1].getClass());

This will tell you what it actually is.

다른 팁

By that explicit cast, you're telling the compiler to trust you that you know what you're doing. Thus, your program compiles but crashes because.. myObj[1] is not a BigDecimal, you fooled the compiler and now his best friend (the JVM) is angry.

  1. Never work with Raw type Collection: declare your collection with proper Generic types of your case: List<BigDecimal[]>
  2. myObj is not likely a BigDecimal[] object, hence a ClassCastException can occur.

Because myObj[1] is not a BigDecimal.

A ClassCastException ocurrs when you try to cast an instance of an Object to a type that it is not.

You are trying to cast an unSupported Object type to a BigDecimal object. i.e. myObj[1] is not a BigDecimal instance.

ClassCastException documenation says that

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top