I ran into a strange case in my application. It's even more strange because it have been runing for few years so far and there wasn't any problem with this but recently we faced the error.
In very simple example my application does something in similar way as code below (but via polymorphism, the result is the same as in example)
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add(listObjectString().get(0));
Object date = list.get(0);
System.out.println(date.getClass()); //OK, prints java.util.Date
Object date2 = list.get(0).getClass(); //ERROR, ClassCastException
System.out.println(date2);
}
public static List<? extends String> listObjectString(){
LinkedList list = new LinkedList();
list.add(new Date());
return list;
}
At this point first case doesn't generate error, but when I try to do the same in a single line I'm getting ClassCastException (Date cannot be cast to String).
I checked ByteCode and in second case there is additional line with CHECKCAST.
Can anyone explain how it works? I couldn't find precise answer. Whats more when I was testing this error in my application I've tried it on two devices with the same Java version and the same configuration and on one device I was getting error but on the other one everything was working fine.
Thank you in advance for any answers, that will definitely brighten me the view of this case a little.