Cast from object type name(String)

Asked

Viewed 80 times

0

I get a list that has several types of Htmlelements. I need a Namevaluepair list, with name and value of each object. So I have this function that gets the list:

    private List getValoresPost(List parametros){
    List<NameValuePair> param = new ArrayList<>();
    parametros.forEach(parametro -> {
        String type = parametro.getClass().getSimpleName();
        param.add(new NameValuePair(((HtmlHiddenInput) parametro).getNameAttribute(), ((HtmlHiddenInput) parametro).getValueAttribute()
        ));
    });
    return param;
}

As I said, each object is of a different type, which I thought: take the name of the type of that object, and pass the cast parameter. In place of the (Htmlhiddeninput) I put the type but as an object. It has as?

1 answer

2


The class HtmlInput (link) is the parent of several classes used in forms (they contain the methods .getNameAttribute() and .getValueAttribute()), with the exception of select, so instead of casting by class name you can do the following to address your problem:

private List getValoresPost(List parametros){
    List<NameValuePair> param = new ArrayList<>();
    parametros.forEach(parametro -> {
        //como a lista não está tipada é bom checar os objetos com instanceof
        HtmlInput input = (HtmlInput) parametro;
        param.add(new NameValuePair(input.getNameAttribute(), input.getValueAttribute()));
        if(parametro.getClass().equals(HtmlSelect.class)) {
            //trata dados de um select (se você precisar)
        }
    });
    return param;
}
  • Exactly that! Thank you very much.

Browser other questions tagged

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