Parijat Bose
Parijat Bose

Reputation: 390

How to find the type of an Object and then work accordingly?

I have a method where i can pass any type of argument. My objective is to find that the argument passed is a number or not and then find the absolute value of the number. The object passed can be double, Integer, string, long, etc.

Demo.java

public class Demo{
public Object abs(Object O){
       if(Number.class.isAssignableFrom(O.getClass())){

    // Check the type of the number and return the absolute value of the number

        }
       else
       {
             return -1
       }
  }

Upvotes: 1

Views: 115

Answers (4)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

If you would like to find the exact type of the object, you can use a chain of if-then-elses, like this:

Class<? extends Object> cls = O.getClass();
if (cls == Integer.class) {
} else if (cls == String.class) {
} else if (cls == Long.class) {
} else if (cls == Double.class) {
} ...

However, this sounds like a poor design choice: consider using overloaded methods in place of a "catch all" method that takes Object to avoid this issue in the first place;

public Double abs(Double O){
   ...
}
public String abs(String O){
   ...
}
public Long abs(Long O){
   ...
}
public Integer abs(Integer O){
   ...
}

Upvotes: 2

aeros
aeros

Reputation: 314

The keyword you're looking for here is probably instanceof

public Object abs(Object O){
   if(Number.class.isAssignableFrom(O.getClass()))
   {

       if(O instanceof Integer) {
            ....
       }
       else if(O instanceof Double) {
            ....
       }
       .....

   }
   else
   {
         return -1
   }

}

Upvotes: 0

PermGenError
PermGenError

Reputation: 46408

Just do an insatnceof test :

if(o insatnceof Integer) {
//abs(int)
}
else if(o instanceof Double){
//abs(double)
}
.....

Upvotes: 2

Rob I
Rob I

Reputation: 5737

Try using the instanceof operator instead.

if ( O instanceof Number ) {
  return Math.abs(((Number)O).doubleValue());
}

Your requirements are getting stretched - is it OK to cast to a double?

See What is the difference between instanceof and Class.isAssignableFrom(...)? for more information.

Upvotes: 0

Related Questions