Java: how to determine the type of an 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: is the first element of the object an instance of the class Integer? or is it a primitive data type int? There is a difference, right?

So, if I want to determine the type of the first element (this is an integer, double, string, etc.), how to do it? Do I use x[0].getClass().isInstance()? (if so, how?), or am I using something else?

+3
source share
4 answers

You want to use the instanceof operator.

eg:

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
}
+4
source

There is a difference between intand Integer, and Integercan only go into Object [], but autoboxing / unboxing makes it difficult to bind it.

, Integer, . , int [] Integer, int , Integer .

+5

xis an array of objects, therefore it cannot contain primitives, only objects, therefore the first element is of type Integer. It becomes Integer using 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")
+5
source

not what you requested, but if someone wants to determine the type of allowed objects in the array:

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

 Class classT = x.getClass().getComponentType(); 
+4
source

Source: https://habr.com/ru/post/1791364/


All Articles