Object type (class) identification

I run into the class misidentifying problem. Scratching my head, I have no clue at all for the cause.

List<MyClass> rl = ...;

for(MyClass e : rl){// <-- java.lang.ClassCastException

logger.debug(e.getId());

}

After I get a list of MyClass objects, how come the ClassCastException is thrown?

If they are not the data type, how I can find out what type of data/object they are?

btw, the list of the objects is retrieved with Hibernate statement which I am quite certain it is correct.

[656 byte] By [vwuvancouvera] at [2007-11-26 17:08:34]
# 1
Whatever expression is being elided by "..." is not returning a list of MyClass objects.
DrLaszloJamfa at 2007-7-8 23:36:25 > top of Java-index,Java Essentials,Java Programming...
# 2

... to see more why not:

List<Object> rl = ...;

for(object x L r1) {

if (x==null)

System.out.println("null");

else

System.out.println(x.getClass());

}

DrLaszloJamfa at 2007-7-8 23:36:25 > top of Java-index,Java Essentials,Java Programming...
# 3

Thanks very much your quick response, Dr. Lasz.

The Eclipse tells me that I can't change the retured type from List<MyClass> to List<Object>. And I get the same exception on

for(Object x : r1) { // <-- here

...

}

I didn't know the ClassCastException could be thrown in an up-casting case.

Message was edited by:

vwuvancouver

vwuvancouvera at 2007-7-8 23:36:25 > top of Java-index,Java Essentials,Java Programming...
# 4

Woops! Maybe the first thing is to check to see if r1 is null, and if not, what class it is an instance of:

if (r1 == null)

System.out.println("r1 is null");

else

System.out.println("r1: " + r1.getClass());

DrLaszloJamfa at 2007-7-8 23:36:25 > top of Java-index,Java Essentials,Java Programming...
# 5

It returns the java.util.ArrayList which is corrent. The issue is an array list of what object. The data is passed to a JSP and causes an exception due to an incorrect data type. From the error message

javax.servlet.jsp.JspException: An error occurred while evaluating custom action attribute "value" with value "${entry.consumer.name}": The "." operator was supplied with an index value of type "java.lang.String"

it seems to be a list of a list/collection. That is something totally weird.

vwuvancouvera at 2007-7-8 23:36:25 > top of Java-index,Java Essentials,Java Programming...
# 6

After doing some study on the Generics, I try out the wildcard type.

List<?> rl = ...;

for(object e : r1) {

if (e == null)

System.out.println("null");

else

System.out.println(e.getClass());

}

And the output

class [Ljava.lang.Object;

class [Ljava.lang.Object;

class [Ljava.lang.Object;

class [Ljava.lang.Object;

Interesting?!

vwuvancouvera at 2007-7-8 23:36:25 > top of Java-index,Java Essentials,Java Programming...
# 7
Okay, you're getting a List< Object[] >. If that is what Hibernate is returning to you, now you know.
DrLaszloJamfa at 2007-7-8 23:36:25 > top of Java-index,Java Essentials,Java Programming...