Passing of several parameters as an Array

4

I have a method that receives an unknown amount of parameters as an Array, like this:

public void enviarCampos(String funcao, String... campos) {
  // Ação do método
}

To call this method I do:

enviarCampos("CADASTRAR", "nome", "dataNascimento", "sexo", "rg", "cpf");

The problem is that I do not know what these parameters will be, they will depend on several conditions, so I can not place them in a fixed position. I put these parameters in a ArrayList , so I can manipulate the parameter list, and tried to cast to call the method, but it did not work:

ArrayList<String> listaCampos = new ArrayList<>(Arrays.asList("nome", "dataNascimento", "sexo", "rg", "cpf"));
enviarCampos("CADASTRAR", (String[]) listaCampos.toArray());

Does anyone know how to do it?

    
asked by anonymous 18.11.2016 / 15:06

1 answer

3

Use the toArray (T [] method) arr) :

ArrayList<String> listaCampos = new ArrayList<>(Arrays.asList("nome", "dataNascimento", "sexo", "rg", "cpf"));
enviarCampos("CADASTRAR", listaCampos.toArray(new String[listaCampos.size()]));
    
18.11.2016 / 15:16