Java:如何确定对象数组中的对象的类型?

问题描述:

实施例:Java:如何确定对象数组中的对象的类型?

Object[] x = new Object[2]; 
x[0] = 3; // integer 
x[1] = "4"; // String 
System.out.println(x[0].getClass().getSimpleName()); // prints "Integer" 
System.out.println(x[1].getClass().getSimpleName()); // prints "String" 

这使我惊奇:第一对象元素是Integer类的实例?或者它是一个原始数据类型int?有区别,对吧?

所以,如果我想确定第一个元素的类型(是一个整数,双精度,字符串等),该怎么做?我使用x[0].getClass().isInstance()? (如果是,如何?),还是我使用别的东西?

您想使用instanceof运算符。

例如:

if(x[0] instanceof Integer) { 
Integer anInt = (Integer)x[0]; 
// do this 
} else if(x[0] instanceof String) { 
String aString = (String)x[0]; 
//do this 
} 

intInteger只有一个Integer之间的差异可以进入一个Object []但自动装箱/拆箱使得它难以确定下来。

一旦你把你的价值在数组中,它被转换为Integer,它的起源被遗忘。同样,如果您声明int []并将其放入Integer,它将被当场转换为int,并且不会保留Integer的痕迹。

+0

+1通过解释的问题题 :) – Dinei 2014-10-12 17:26:28

x是一个对象数组 - 因此它不能包含基元,只包含对象,因此第一个元素的类型是Integer。它会成为自动装箱的整数,如@biziclop说

要检查一个变量的类型,使用instanceof

if (x[0] instanceof Integer) 
    System.out.println(x[0] + " is of type Integer") 

你问不算什么,但如果有人想确定类型允许在一个阵列对象:

Oject[] x = ...; // could be Object[], int[], Integer[], String[], Anything[] 

Class classT = x.getClass().getComponentType();