java.lang.Classcastexception: Converter JSF error

Asked

Viewed 498 times

2

I am 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 "";
    }

}

On the 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;

The model is also implemented hasCode.

How to solve 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)
  • 1

    What exception? I guess you forgot to include it

  • value is already coming to you like a Long, then you don’t have to do cast for an object Cargo and then retrieve the id

1 answer

2


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’s happening is you try to do cast of an object Long for a Cargo. value in getAsString is already coming to you as Long, probably is the id that waits and needs, so it is not necessary (nor possible) to do cast for the guy Cargo, you can change it:

@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();
}

Already considering the final value. The question is how Object you’re returning a Cargo. I do not know how the rest of your application is, especially the places that use this convert, but perhaps here it is necessary to return the id of Cargo also.

Browser other questions tagged

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