繁体   English   中英

出现错误,例如使用未经检查或不安全的操作

[英]Getting Error like uses unchecked or unsafe operations

获取错误使用未经检查或不安全的操作。 在我更新了一些android studio firebase库之后。

logcat中出现错误是...使用未经检查或不安全的操作。 使用-Xlint重新编译:未经检查以获取详细信息。

public class UserId
{
    public String userId;
    public<T extends UserId> T withDocId(@Nullable final String id)
    {
        this.userId=id;
        return (T) this;
    }

}

强制转换为类型参数是不安全的类型转换。 实际上,在这种情况下,在运行时进行的类型检查是

return (UserId) this;

可是等等。 该类型的thisUserId ... ...和类型参数未达到任何东西。 该类可以简化为:

public class UserId {
    public String userId;
    public UserId withDocId(@Nullable final String id) {
        this.userId = id;
        return this;
    }
}

(T)是不安全的,因为在Java中,泛型类型会遭到类型擦除,这意味着它们作为编译时类型安全性强制措施。 在运行时,没有名为T类,因此编译器不可能生成可以转换为T的字节码指令。

由于没有办法知道在编译时什么类型this实际上是(除了知道它必须是用户ID或子类用户ID),你不能一个泛型类型适用于this

您可以让用户传递他们期望的UserId类型,尽管这很尴尬:

public <T extends UserId> T withDocId(@Nullable final String id,
                                      Class<T> userIdType)
{
    this.userId = id;
    return userIdType.cast(this);
}

另一种可能性是重写每个子类中的方法。

public class UserId
{
    public UserId withDocId(@Nullable final String id)
    {
        this.userId = id;
        return this;
    }
}

public class ManagerId
extends UserId
{
    @Override
    public ManagerId withDocId(@Nullable final String id)
    {
        super.withDocId(id);
        return this;
    }
}

这是允许的,因为返回较小类型集的子类与超类定义完全兼容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM