java - 为什么抑制这个未经检查的警告是安全的?

标签 java generics effective-java

考虑 UnaryFunction Effective Java 泛型章节中定义的接口(interface)。

public interface UnaryFunction<T> {
T apply(T arg);
}

和以下用于返回 UnaryFunction 的代码

// Generic singleton factory pattern
private static UnaryFunction<Object> IDENTITY_FUNCTION = new UnaryFunction<Object>() {
  public Object apply(Object arg) { return arg; }
};

// IDENTITY_FUNCTION is stateless and its type parameter is
// unbounded so it's safe to share one instance across all types.
@SuppressWarnings("unchecked")
public static <T> UnaryFunction<T> identityFunction() {
  return (UnaryFunction<T>) IDENTITY_FUNCTION;
}

为什么是IDENTITY_FUNCTION的cast至 (UnaryFunction<T>)安全吗?

这本书是关于我要问的问题的,但我不能遵循这里的逻辑。我们在哪里调用 apply执行身份操作的功能?我很困惑,因为正是这个函数返回传递给它的相同对象而不修改任何东西。

The cast of IDENTITY_FUNCTION to (UnaryFunction<T>) generates an unchecked cast warning, as UnaryFunction<Object> is not a UnaryFunction<T> for every T. But the identity function is special: it returns its argument unmodified, so we know that it is typesafe to use it as a UnaryFunction<T> whatever the value of T. Therefore, we can confidently suppress the unchecked cast warning that is generated by this cast. Once we’ve done this, the code compiles without error or warning.

最佳答案

仅当身份函数返回一开始传递给它的精确对象时,转换才是安全的。因此,在运行时,不存在可能违反强制转换的通用参数 T 的特化。

也就是说,您正在将一个对象转换为它自己的类型。

关于java - 为什么抑制这个未经检查的警告是安全的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15071851/

相关文章:

java - 以 json 格式写入文件时出错。Stream 已关闭

java - 为什么 TreeSet 声明为 TreeSet<E> 而不是 TreeSet<E extends Comparable<E>>

java - 如何让 Spring 打印出哪些 Spring 配置文件处于 Activity 状态?

swift - 为未命名的默认参数传递通用结构会导致垃圾属性

c# - 为什么不能将 List<Derived> 分配给 List<Base>?

java - 了解有效的 Java 深拷贝示例

java - Eclipse 中通用类型的自动完成

java - 为 future 可能的可扩展性保留一个非最终值类

java - 设置 Jersey 时出错

java - 是否可以在Java中为每个pcollection编写不换行的代码?