考虑 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, asUnaryFunction<Object>
is not aUnaryFunction<T>
for everyT
. But the identity function is special: it returns its argument unmodified, so we know that it is typesafe to use it as aUnaryFunction<T>
whatever the value ofT
. 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/