i found a (for my state of knowledge) strange behavior during the adding of a Class type to a list.
I have a list which holds all implementing classes of an Abstract class List<Class<MyAbstractClass>> myImplementations. I added a type of a non-derived class and there was no error. Can anyone explain why i can do something like myImplementations.add(SomeOtherClass.class); without any exception? It seems that the second generic type (MyAbstractClass) has no effect at all.
— edit —
public abstract class MyAbstractClass{
public static String getMyIdentification(){ throw new RuntimeException("implement method");}
}
public class MyImplementation extends MyAbstractClass{
public static String getMyIdentification(){ return "SomeUUID";}
}
public class OtherClass{}
// in another class:
List<Class<MyAbstractClass>> myImplementations = new ArrayList<Class<MyAbstractClass>>();
myImplementations.add(MyImplementation.class); // does not cause any error
myImplementations.add(OtherClass.class); // does not cause any error, but should in my opinion??
—- edit end —
Thank you,
el
The type is erased during compilation, so you won’t see any exception at runtime. The compiler should complain in your case or give a warning.
The type parameter
Class<String>is erased during compilation – it is only used by the compiler to check if the java source code is valid. The compiled bytecode doesn’t contain this information anymore, on byte code level the list will hold and acceptObjector any subclass ofObject. And becauseInteger.classis a subclass ofObject, the code will run – until the runtime throws ClassCastExceptions at the programmer, just because it expectedClass<String>instances.