Skip to content
Advertisement

Tag: classcastexception

ClassCastException “Parent cannot be cast to class…are in unnamed module of loader ‘app’ ” with Java Generics and inheritance

I´m currently facing a problem with generics in Java. I need to return a parent instance casted to the child. The sample below shows what I´m trying to achieve. This code does not run through and produces this exception instead: class com.generics.GenericTest$Parent cannot be cast to class com.generics.GenericTest$ChildEntity (com.generics.GenericTest$Parent and com.generics.GenericTest$ChildEntity are in unnamed module of loader ‘app’) java.lang.ClassCastException: class

Java strange class cast exception

Could anyone help me understand why in 1 situation I do not have ClassCastException? At least String::trim is not a MagicFunction. Answer So, method references (like String::trim) are a bit weird; unlike most expressions in Java, they don’t really have a type of their own. Something like this: won’t even compile, because it doesn’t give the compiler enough information about

Advertisement