Finding the object class in Java

0

I have a set of functions to configure a set of parameters in Java of type like this:

public void Util.setParametros(Integer par) {}
public void Util.setParametros(String par) {}
public void Util.setParametros(Long par) {}
public void Util.setParametros(Double par) {}
public void Util.setParametros(Boolean par) {}

Now I have another function that uses this and it gets an array of parameters with the various types it has. For example:

public List buscaPorWhere(String where, Object[] parametros)

And I would need to know what type it is to be able to call the method like this:

Util.setParametros((Integer) parametros[1]);

How could I do this?

    
asked by anonymous 29.06.2015 / 19:13

1 answer

4

You can do with instanceof

Since there are few types you need to check out you can do something like this:

for(Object p: parametros){
   if(p instanceof Integer){
      Util.setParametros((Integer) p);
      //...
   }
   else if(p instanceof String){
      Util.setParametros((String) p);
      //faz algo aqui;   
   }
   else if.... //por ai vai
}

EDIT: OPTION 2 Another option is to look for a way to use the switch case to avoid the chained if. It could be like this:

 for(Object p: parametros){
       String className = p.getClass().getSimpleName();
       switch(className){
          case "Integer":
             //...
             break;
          case "String":
             //...
             break;
            ....
     }
    
29.06.2015 / 19:22