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[]
java.lang.ClassCastExcepti on: [Ljava.lang.Object; cannot be cast to [Ljava.lang.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();
This fixes it:Class[] taskClasses = (Class[]) tempOutList.toArray();
but I don't understand why this is necessary. Even so, it gives a runtime error:java.lang.ClassCastExcepti
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
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
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);
}
Class[] taskClasses = new Class[tempList.size()];
for (int j=0; j<tempList.size(); j++) {
taskClasses[j] = tempList.get(j);
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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