[英]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:显然只有当T
是 String 类型时才会调用conevertDataToJSONString
方法。但是有一个警告:
Type safety: Unchecked cast from String to T类型安全:从 String 到 T 的未经检查的强制转换
Is there a way to solve that without using SuppressWarnings
:有没有办法在不使用SuppressWarnings
情况下解决这个问题:
@SuppressWarnings("unchecked") @SuppressWarnings("未选中")
before method?之前的方法?
Seemingly, you can use Class.cast(Object)
since you have the Class<T>
already:看起来,您可以使用Class.cast(Object)
因为您已经拥有Class<T>
:
@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.但是,您对if(type.equals(String.class))
让我感到疑惑——因为这意味着您对T
实际是什么有一些预知。 You should perhaps read "Why Use Generics?"您或许应该阅读“为什么使用泛型?” and consider whether generics are really the correct solution here.并考虑泛型在这里是否真的是正确的解决方案。
you must convert string to T by this code:您必须通过以下代码将字符串转换为 T:
String value = gson.toJson(data);
T elem = transformer.transform(value);
return T;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.