[英]Java: how to determine type of object in an array of objects?
Example: 例:
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"
This makes me wonder: the first object element is an instance of class Integer
? 这让我想知道:第一个对象元素是Integer
类的实例? or is it a primitive data type int
? 或者它是原始数据类型int
? There is a difference, right? 有区别,对吧?
So if I want to determine the type of first element (is it an integer, double, string, etc), how to do that? 所以,如果我想确定第一个元素的类型(是整数,双精度,字符串等),该怎么做? Do I use x[0].getClass().isInstance()
? 我是否使用x[0].getClass().isInstance()
? (if yes, how?), or do I use something else? (如果是,怎么样?),还是我用别的东西?
There is a difference between int
and Integer
and only an Integer
can go into an Object []
but autoboxing/unboxing makes it hard to pin it down. int
和Integer
之间有区别,只有一个Integer
可以进入Object []
但是autoboxing / unboxing会很难将其固定下来。
Once you put your value in the array, it is converted to Integer
and its origins are forgotten. 一旦将值放入数组中,它就会转换为Integer
并且它的起源会被遗忘。 Likewise, if you declare an int []
and put an Integer
into it, it is converted into an int
on the spot and no trace of it ever having been an Integer
is preserved. 同样,如果你声明一个int []
并将一个Integer
放入其中,它会在现场转换为一个int
,并且不会保留它的Integer
。
x
is an object array - so it can't contain primitives, only objects, and therefore the first element is of type Integer. x
是一个对象数组 - 因此它不能包含基元,只能包含对象,因此第一个元素的类型为Integer。 It becomes an Integer by autoboxing, as @biziclop said 正如@biziclop所说,它通过自动装箱成为一个整数
To check the type of a variable, use instanceof
: 要检查变量的类型,请使用instanceof
:
if (x[0] instanceof Integer)
System.out.println(x[0] + " is of type Integer")
You want to use the instanceof operator. 您想使用instanceof运算符。
for instance: 例如:
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
}
not what you asked, but if anyone wants to determine the type of allowed objects in an array: 不是你问的,但是如果有人想确定数组中允许的对象的类型:
Oject[] x = ...; // could be Object[], int[], Integer[], String[], Anything[]
Class classT = x.getClass().getComponentType();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.