为什么我必须转换为Generic Type T即使我知道它返回正确?

Say*_*iss 7 java generics

我的代码:

private static <T> T get(Class<T> clazz) throws IllegalAccessException, InstantiationException {
        if (clazz.equals(String.class)) {
            return (T) new String("abc");//line x
        } else {
            return clazz.newInstance();
        }

    }
Run Code Online (Sandbox Code Playgroud)

如你所见,in line x,T必须String.class和返回String.但编译失败而不将结果转换为T.

更改line xreturn new String("abc");的结果Incompatible types.

Thi*_*ilo 5

编译器不考虑该if语句.

所以它看到的只是你需要返回一个T(它没有进一步的知识).它没有推断T必须在String这里.

您可以通过执行操作避免出现"未经检查的强制转换为已擦除类型"的警告

return clazz.cast("abc");
Run Code Online (Sandbox Code Playgroud)