Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out if a Object is a integer or is a string or is a boolean?

Tags:

java

I have an object and I want to detect what type is, so I can call

if (obj isa Integer)
  put(key,integerval);  
if (obj isa String)
    put(key,stringval);  
if (obj isa Boolean)
    put(key,booleanval);
like image 388
Pentium10 Avatar asked Mar 06 '10 09:03

Pentium10


1 Answers

You're pretty close, actually!

if (obj instanceof Integer)
    put(key,integerval);  
if (obj instanceof String)
    put(key,stringval);  
if (obj instanceof Boolean)
    put(key,booleanval);

From the JLS 15.20.2:

RelationalExpression instanceof ReferenceType

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast (§15.16) to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

Looking at your usage pattern, though, it looks like you may have bigger issues than this.

like image 140
polygenelubricants Avatar answered Sep 22 '22 02:09

polygenelubricants