简体   繁体   中英

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 ? or is it a primitive data type 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() ? (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.

Once you put your value in the array, it is converted to Integer and its origins are forgotten. 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.

x is an object array - so it can't contain primitives, only objects, and therefore the first element is of type Integer. It becomes an Integer by autoboxing, as @biziclop said

To check the type of a variable, use instanceof :

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

You want to use the instanceof operator.

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(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM