- Java中数组是一个类,父类是object。所以数组强制转换能把 instanceof为真的object强转为数组。
- 注意:虽然数组的父类是object。但可以用Object[]指向String[],并且instanceof为真,即可强转成String[]。
Object object = new String[]{"object cast"};
Object[] objects = new String[]{"object[] cast"};
if(object instanceof String[])
{
System.out.println("object instanceof is true");
String[] strings= (String[]) object;
System.out.println(strings[0].toUpperCase());
}
else {
System.out.println("object instanceof is false");
}
if(objects instanceof String[])
{
System.out.println("objects instanceof is true");
String[] strings= (String[]) objects;
System.out.println(strings[0].toUpperCase());
}
else {
System.out.println("instanceof is false");
}
- 实际上:可以两层强转:String[] → Object[] → Object。但注意,数组的唯一父类依旧是Object。
Object[] objects = new String[]{"both cast"};
System.out.println(objects.getClass().getSuperclass());
Object object = objects;
if(object instanceof Object[] && object instanceof String[])
{
System.out.println("instanceof is true");
String[] strings= (String[]) object;
System.out.println(strings[0].toUpperCase());
}
else {
System.out.println("object instanceof is false");
}
4. 其实这种关系可以这样表述: 如果有两个类A和B,如果B继承(extends)了A,那么A[]类型的引用就可以指向B[]类型的对象。
详情见