Java 获取错误,如使用未检查或不安全的操作
获取错误使用未检查或不安全的操作。在我更新了一些android studio firebase库之后 在logcat中获取错误是。。。 使用未经检查或不安全的操作。 使用-Xlint重新编译:未选中以获取详细信息Java 获取错误,如使用未检查或不安全的操作,java,Java,获取错误使用未检查或不安全的操作。在我更新了一些android studio firebase库之后 在logcat中获取错误是。。。 使用未经检查或不安全的操作。 使用-Xlint重新编译:未选中以获取详细信息 public class UserId { public String userId; public<T extends UserId> T withDocId(@Nullable final String id) { this.us
public class UserId
{
public String userId;
public<T extends UserId> T withDocId(@Nullable final String id)
{
this.userId=id;
return (T) this;
}
}
公共类用户ID
{
公共字符串用户标识;
带docid的公共T(@Nullable final String id)
{
this.userId=id;
返回(T)这个;
}
}
对类型参数的转换是不安全的类型转换。事实上,在本例中,运行时发生的类型检查是
return (UserId) this;
但是等等。此
的类型为UserId
。。。类型参数没有实现任何功能。课程可以简化为:
public class UserId {
public String userId;
public UserId withDocId(@Nullable final String id) {
this.userId = id;
return this;
}
}
(T)
是不安全的,因为在Java中,泛型类型会受到类型擦除的影响,这意味着它们只能作为编译时类型安全强制。在运行时,没有名为T
的类,因此编译器不可能生成可以转换为T
的字节码指令
由于在编译时无法知道此的实际类型(除了知道它必须是UserId或UserId的后代类之外),因此不能将泛型类型应用于此
您可以让用户传递他们期望的用户ID类型,尽管这相当尴尬:
public <T extends UserId> T withDocId(@Nullable final String id,
Class<T> userIdType)
{
this.userId = id;
return userIdType.cast(this);
}
这是允许的,因为返回较小类型集的子类与超类定义完全兼容。是否使用-Xlint:unchecked重新编译以获取详细信息?
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;
}
}