java.lang.ClassCastException: Error in JSF Converter

1

I'm implementing the Converter below:

@FacesConverter(forClass = Cargo.class)
public class CargoConverter implements Converter {

    @Inject
    private CargosRepository cargoRepository;

    public CargoConverter() {
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        Cargo retorno = null;

        if (value != null) {
            retorno = this.cargoRepository.porId(new Long(value));
        }
        return retorno;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value != null) {
            Long id = ((Cargo) value).getId();
            String retorno = (id == null ? null : id.toString());
            return retorno;
        }
        return "";
    }

}

At line Long id = ((Cargo value).getId() is giving the exception above.

My model is implemented like this:

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;

In the model hasCode also implemented.

How to resolve this exception? What am I doing wrong?

Exception:

java.lang.ClassCastException: java.lang.Long cannot be cast to com.porto.npf.sgpsweb.model.Cargo
    at com.porto.npf.sgpsweb.converter.CargoConverter.getAsString(CargoConverter.java:31)
    
asked by anonymous 13.10.2015 / 02:47

1 answer

1

Considering the exception:

java.lang.ClassCastException: java.lang.Long cannot be cast to com.porto.npf.sgpsweb.model.Cargo
    at com.porto.npf.sgpsweb.converter.CargoConverter.getAsString(CargoConverter.java:31)

What is happening is that you try to cast cast from an object Long to a Cargo . value in getAsString is already arriving to you as Long , it is probably the id you expect and need, so it is not necessary (and not even possible) to do cast for type Cargo , you can change this:

@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
    if (value != null) {
        Long id = ((Cargo) value).getId();
        String retorno = (id == null ? null : id.toString());
        return retorno;
    }
    return "";
}

For this:

@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
    return value == null ? "" : value.toString();
}

Considering the final value. The issue is that as Object you are returning Cargo . I do not know how the rest of your application is, especially the places using this convert , but maybe here it is necessary to return id of Cargo too.

    
13.10.2015 / 13:45