Link to home
Start Free TrialLog in
Avatar of allelopath
allelopath

asked on

Class cast problem

In the code below, the last line is giving a compile error, saying that it cannot from Object[] to Class[]
Class[] tempTaskClasses = Reflection.getPackageMembers("com.mycompany.mypackage");
List<Class> tempList = Arrays.asList(tempTaskClasses);
List<Class> tempOutList = new ArrayList<Class>();
    for (Class myClass : tempList) {
 		tempOutList.add(myClass);
    }
 	
}
Class[] taskClasses =  tempOutList.toArray();

Open in new window

This fixes it:
Class[] taskClasses =  (Class[]) tempOutList.toArray();

Open in new window

but I don't understand why this is necessary. Even so, it gives a runtime error:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Class;
Avatar of for_yan
for_yan
Flag of United States of America image

Becuase
toArray() method of the List produces array of Objects

http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#toArray%28%29

so you eed to cast it to arrayr of object of scertain type Class which are suvlcalsses
of Object and downcast requires expliscit cast
if toArray() method would have been producing array of Class oinstances
it wouyld be fine and would not have required it,
but the method produces array of Object instances - so you need to cast them to subclass
Even if you have generic List<Class> it still produces array of Object instances in the toArray() method.

That probably is because genrics are not inherinting, so that ArrayList<Class> in Java is not subclass of ArrayList<Object>, that;s why this method returns only arry of Object's

So you have to cast
this would of course work:

Class[] taskClasses = new Class[tempList.size()];

  for (int j=0; j<tempList.size(); j++) {
             taskClasses[j] = tempList.get(j);
    }
ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial