从列表中获取对象时
我在应用程序中遇到了一个奇怪的情况。它更加奇怪,因为到目前为止,它已经运行了几年,而且没有任何问题,但是最近我们面临了错误。
在非常简单的示例中,我的应用程序以与下面的代码相似的方式执行某些操作 (但是通过多态性,结果与示例中的结果相同)
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;
}
在这一点上,第一种情况尚未产生错误,但是当我尝试在一行中进行相同的操作时,我会得到classcastException(无法将日期施加到字符串)) 。
我检查了字节码,在第二种情况下,还有其他签名广播。
谁能解释它是如何工作的?我找不到精确的答案。 当我在应用程序中测试此错误时,还有什么问题在具有相同Java版本和相同配置的两个设备上尝试了它,并且在一种设备上,我遇到了错误,但另一个设备都可以正常工作。
预先感谢您的任何答案,这肯定会使我对这种情况有所了解。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论