java - 在运行时解析泛型变量时如何避免未经检查的强制转换?

标签 java generics casting type-safety

我有一个参数化值,在运行时解析:

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/

相关文章:

objective-c - 如何将 NSString 初始化为 NSMutableString?

c - 这是检查 C 中转换操作数据丢失的好方法吗?

java - 驱动服务器意外死机了!含 Selenium

java - If 语句搜索特定字符

java - Java 中的泛型——实现接口(interface)

java通用字符串到<T>解析器

generics - 在 TypeScript 泛型中使用 "extends"关键字

java - Hadoop 2.0 JAR文件

java - Spark Java API如何计算总工资

C++ 隐式数字类型降级