Cast from the name (String) of the object type

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: get the type name of that object, and pass in the cast parameter. In place of (HtmlHiddenInput) I put the type but as object. How?

    
asked by anonymous 12.12.2017 / 15:43

1 answer

2

The HtmlInput class ( link ) is a parent of several classes used in forms (they contain the methods .getNameAttribute() and .getValueAttribute() ), with the exception of select , then instead of doing cast by the class name you can do the following to treat 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;
}
    
12.12.2017 / 19:07