我有一个参数化值,在运行时解析:
public class GenericsMain {
public static void main(String... args) {
final String tag = "INT";
Field field = resolve(tag);
if (tag.equals("INT")) {
/*
In here I am using the "secret knowledge" that if tag equals INT, then
field could be casted to Field<Integer>. But at the same time I see an unchecked cast
warning at here.
Is there a way to refactor the code to be warning-free?
*/
Field<Integer> integerField = (Field<Integer>) field;
foo(integerField);
}
}
public static Field resolve(String tag) {
switch (tag) {
case "INT":
return new Field<>(1);
case "DOUBLE":
return new Field<>(1.0d);
default:
return null;
}
}
public static <T> void foo(Field<T> param) {
System.out.println(param.value);
}
static class Field<T> {
public final T value;
public Field(T value) {
this.value = value;
}
}
}
有没有办法避免上面代码中的unchecked cast(标有长注释)?
最佳答案
一般来说,没办法,因为类型参数绑定(bind)到声明。而您想要做的是根据运行时值更改静态声明。
但是,您可以通过声明添加类型参数的参数化方法来最小化未检查转换的区域
@SuppressWarnings("unchecked")
private static <T> Field<T> asParameterized(Field<?> field) {
return (Field<T>) field;
}
然后使用
Field<Integer> intField = GenericsMain.<Integer> asParameterized(field);
关于java - 在运行时解析泛型变量时如何避免未经检查的强制转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33477449/