将超类型的数组转换为子类型 [英] Casting arrays of a supertype to a subtype
本文介绍了将超类型的数组转换为子类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Java中导致运行时异常而不是编译时错误的原因是否存在?
Is there a particular reason why this results in runtime exception instead of compile-time error in Java?
Object[] objects = new Object[10];
String[] strings = (String[])objects;
推荐答案
由于以下原因,必须在运行时进行检查:这种情况:
The check has to be done at run time because of this case:
public class Test {
public static void main(String[] args){
String[] stringsBase = {"aaa", "bbb", "ccc"};
Object[] objects = stringsBase;
String[] strings = (String[])objects;
System.out.println(strings[1]);
}
}
这是一个有效的工作程序。如果不进行流分析,编译器将不知道对象是引用创建为Object []的数组,还是引用为String []的数组。
This is a valid, working program. Without doing flow analysis, the compiler does not know whether objects references an array that was created as Object[], or one that was created as, in this case, a String[].
这篇关于将超类型的数组转换为子类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文