Is it possible to type cast to a parent abstract class?
-
29-09-2019 - |
Question
I'm in the process of porting a C# project into Java. I've got a chunk of code that looks like this:
public abstract class A
{
public abstract void foo() throws Exception;
public abstract void bar();
}
And then, elsewhere...
public class FirstOuterClass {
public class FirstInnerClass extends A {
// defines foo() and bar()
}
}
Further elsewhere...
public class SecondOuterClass {
public class SecondInnerClass extends A {
// defines foo() and bar()
}
}
And finally, even MORE elsewhere....
HashMap<Type, A> handlers = new HashMap<Type, A>();
for (Entry e : HashMapOfStringToEntry.getTypes())
{
if(e.Handler != null) {
handlers.put(e.Type, (A) e.Handler);
}
}
e.Handler can be either a type of FirstInnerClass or SecondInnerClass. It's that conversation e.Handler to (A) that is causing the following error:
java.lang.ClassCastException: java.lang.Class
I've verified with debugging output that e.Handler is indeed a class type of FirstOuterClass$FirstInnerClass. So either there are differences in casting between C# & Java (possible) or I am not providing the right syntax somewhere (also possible).
(I'm sorry for not pasting the whole code, like what the HashMaps are for. I don't want to muddle up the real issue. Basically it's a mapping between a String key and a couple of classes that extend abstract A.)
Solution
If one of your inner classes was failing to cast to A
, then your exception would look like:
java.lang.ClassCastException: FirstOuterClass$FirstInnerClass cannot be cast to A
Instead, you're getting this:
java.lang.ClassCastException: java.lang.Class
Are you cutting off "cannot be cast to A" at the end of this?
Regardless, it appears that e.Handler
is of type java.lang.Class
. As in, FirstOuterClass$FirstInnerClass
itself rather than a single instance of it.
OTHER TIPS
From the exception message, it appears that you are trying to cast an instance of Class
, not an instance of the class it represents.