Raghuveer
Raghuveer

Reputation: 3057

Java Generics : Cannot convert from Object to T

I have many response objects that I need to give to ui. I want to have a template so that I can do it, so far below code has not worked.

private <T> T getResult(Class clazz){
    String fileName = "/path/file.json";
    File file = new File(BaseEndpoint.class.getResource(fileName.getFile());
    T result = null;

    try {
        result = mapper.readValue(file, clazz);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return result;
}

Upvotes: 6

Views: 8249

Answers (2)

Andrew
Andrew

Reputation: 49606

T can be not Object. For instance, it might be BaseEndpoint because it meets the condition T extends Object.

You need to cast the result of mapper.readValue(file, clazz) to T:

result = (T)mapper.readValue(file, clazz);

and put @SuppressWarnings("unchecked") over the method if you are sure that this unchecked cast is accurate:

@SuppressWarnings("unchecked")
private <T> T getResult(Class clazz) { ... }

Actually, the cast can be done for you within the readValue method (if it takes Class<T>) so you won't need any of above.

Yes, I have checked it out:

@SuppressWarnings("unchecked")
public <T> T readValue(JsonParser p, Class<T> valueType)
    throws IOException, JsonParseException, JsonMappingException
{
    DeserializationContext ctxt = createDeserializationContext(p);
    return (T) _readValue(ctxt, p, _typeFactory.constructType(valueType));
}

It all will be done for you. You only have to pass a correct Class<T> instance (not the raw type Class)

Upvotes: 9

Sajit Gupta
Sajit Gupta

Reputation: 108

You cannot assign an Object type to type T variable. You will have to cast it explicitly to type T. You should use the following :

result = (T) mapper.readValue(file, clazz);

Upvotes: -1

Related Questions