java:如何修复 Unchecked cast 警告

标签 java generics casting

我有以下代码:

private HashMap<Class<?>, HashMap<Entity, ? extends Component>> m_componentStores;

public <T extends Component> T getComponent(Entity e, Class<T> exampleClass)
{
    HashMap<Entity, ? extends Component> store = m_componentStores.get(exampleClass);

    T result = (T)store.get(e);

    if (result == null)
    {
        throw new IllegalArgumentException( "GET FAIL: "+e+" does not possess Component of class\nmissing: "+exampleClass );
    }

    return result;
}

当我编译时,它显示 T result = (T)store.get(e) 有一个未经检查的类型转换。

Type safety: Unchecked cast from capture#2-of ? extends Component to T

为了防止出现此警告,我缺少什么?

最佳答案

Class.cast 是你想要的。好吧,你可以考虑不使用反射。

换行:

T result = (T)store.get(e);

到:

T result = exampleClass.cast(store.get(e));

关于java:如何修复 Unchecked cast 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4388054/

相关文章:

c# - C# 中的类声明

C# 不寻常的继承语法 w/generics

ios - 在 Swift 中使用泛型无法将“对象”转换为 'T'

c - 如何将字符数组转换为 uint8_t

c++ - dynamic_cast 导致 bad_cast 错误

go - 在 Go 中将数组中的多个字节转换为另一种类型

java - 使用 jcraft.jsch 更改目录时文件夹不存在

java - 将对象从一个类移动到另一个类 (Java)

java - 如何在 BeanWrapperFieldSetMapper 中转换多个日期?

java - 在 Play Framework 项目中删除 IntelliJ 中的错误指示