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.
题
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.
List<BigDecimal[]>
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.