I am writing a program in which I am being forced to use things like this:
HashMap<String,Object> valores = new HashMap<>();
valores.put("valor1", "abc"); // Se guarda como objeto String
valores.put("valor2", (int) 123); // Se guarda como objeto Integer
valores.put("valor3", (double) 3.1416); // Se guarda como objeto Double
Now in another part of the code I need to save these values to a database. I'm using a prepared statement, and I'd like to do something like this:
ps = conn.preparedStatement("insert into tbl (v1, v2, v3) values (?,?,?)")
for(int i = 1; i <= 3; i++) {
if(/*valores.get(String.format("valor%d",i)) es String*/)
ps.setString(i, (String) valores.get(String.format("valor%d",i)));
else if(/*valores.get(String.format("valor%d",i)) es Integer*/)
ps.setInt(i, (Integer) valores.get(String.format("valor%d",i)));
else if(/*valores.get(String.format("valor%d",i)) es Double*/)
ps.setDouble(i, (Double) valores.get(String.format("valor%d",i)));
}
So my specific question is: How can I, at runtime, get the type of a variable saved as Object
?
Your friend's name is
instanceof
, (taken from here and here ).Having a type variable
Object
you can get the internal data type stored in it in the following way:Result:
What applied to your current code would look like this:
I can only imagine that they are pointing a gun at you :-)
The truth is that it is horrible (including the "value1", "value2"...)
But, if you really are forced to do that, then you don't need to find out the actual type at runtime (NaCL's answer in this sense is correct), you can directly use setObject() , Java has a default mapping of its types to the SQL types which in your case (and assuming you don't use more types than those) should reach.
PS: By the way, regarding
instanceof
: itinstanceof
's not really used to get the type/class of an object, but to verify that the object is of a certain type. And "being of a certain kind" means that the real kind is that or a descendant. For example, in your caseinstanceof Number
it will return true when the value is Integer or Double , (both extendNumber
, and therefore "are a Number", even though their true class is something else). If you want to get the concrete class you should useobject.getClass()
.I don't know if it will work for you, but if by type you mean the class of the variable you can simply do:
This will return an object of type Class.