hasanghaforian
hasanghaforian

Reputation: 14022

Type safety: Unchecked cast in generic class

I have a Generic class.It looks like this:

public class DataConverter<T> implements Converter<T> {

    @Override
public T convert(Class<T> type, Object value) {
    if ((type.equals(String.class)) && ... ) {
        return conevertDataToJSONString((Data) value);
    } 
    ...
}

    private T conevertDataToJSONString(Data data) {
        String value = gson.toJson(data);
        return (T) value; // << Type safety: Unchecked cast from String to T
    }
...
}

Obviously conevertDataToJSONString method only called when T be of String type.But there is a warning:

Type safety: Unchecked cast from String to T

Is there a way to solve that without using SuppressWarnings:

@SuppressWarnings("unchecked")

before method?

Upvotes: 0

Views: 3016

Answers (2)

Mohsen Bahaloo
Mohsen Bahaloo

Reputation: 287

you must convert string to T by this code:

String value = gson.toJson(data);
T elem = transformer.transform(value);
return T;

Upvotes: 0

Radiodef
Radiodef

Reputation: 37845

Seemingly, you can use Class.cast(Object) since you have the Class<T> already:

@Override
public T convert(Class<T> type, Object value) {
    if ((type.equals(String.class)) && ... ) {
        //     casting here
        return type.cast( conevertDataToJSONString((Data) value) );
    } 
    ...
}

// no need to make this method generic
private String conevertDataToJSONString(Data data) {
    return gson.toJson(data);
}

However, your use of if(type.equals(String.class)) makes me wonder—because it means you have some foreknowledge of what T actually is. You should perhaps read "Why Use Generics?" and consider whether generics are really the correct solution here.

Upvotes: 6

Related Questions