Discover the object class in Java

Asked

Viewed 3,521 times

1

I have a set of functions to configure a set of parameters in Java 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 receives an array of parameters with the various types it has. For example:

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

And I’d need to know what kind he is so I could call the method that:

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

How could I do that?

1 answer

5


You can do using instanceof

As there are few types you need to check 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 find a way to use the switch case to avoid chained if. It could be like this:

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

    getName() nay. getSimpleName() yes.

  • I’ll edit the answer

  • 2

    And note that String Switch only works from Java SE 1.7

Browser other questions tagged

You are not signed in. Login or sign up in order to post.