为什么要压制这种未经检查的警告是安全的? [英] Why is it safe to suppress this unchecked warning?
问题描述
考虑 Effective Java 泛型章节中定义的 UnaryFunction
接口。
public interface UnaryFunction< T> {
T apply(T arg);
}
以及下面的返回 UnaryFunction
$ pre $ code $ //通用单例工厂模式
private static UnaryFunction< Object> IDENTITY_FUNCTION = new UnaryFunction< Object>(){
public Object apply(Object arg){return arg; }
};
// IDENTITY_FUNCTION是无状态的,其类型参数是
//无界,所以在所有类型中共享一个实例是安全的。
@SuppressWarnings(unchecked)
public static< T> UnaryFunction< T> identityFunction(){
return(UnaryFunction< T>)IDENTITY_FUNCTION;
$ b $ IDENTITY_FUNCTION
to (UnaryFunction< T>)
安全吗?
apply
函数?
将IDENTITY_FUNCTION强制转换为<$ c因为
UnaryFunction< Object>
不是$ b $,所以$ c>(UnaryFunction< T>)产生
unchecked cast警告对于每个T
,bUnaryFunction< T>
。但是身份函数是特殊的:它
返回未修改的参数,所以我们知道使用
它作为UnaryFunction< T>
无论T
的值如何。因此,我们可以
自信地抑制
生成的未经检查的转换警告。一旦我们完成了这些工作,代码就会无错地编译或
警告。
只有当身份函数首先返回传递给它的 精确 对象时,演员才是安全的。因此,在运行时,通用参数 T
没有专门化可以违反演员表。
Aka ,您正在投射一个对象,因为它是自己的类型。
Consider the UnaryFunction
interface defined in Effective Java generics chapter .
public interface UnaryFunction<T> {
T apply(T arg);
}
and the following code for returning the 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;
}
Why is the cast of IDENTITY_FUNCTION
to (UnaryFunction<T>)
safe ?
The book says this about the question I am asking but I can't follow the logic here . Where are we invoking the apply
function which does the identity operation ? i am confused because it is that function which returns the same object passed into it without modifying anything .
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.
The cast is safe insomuch only as the identity function returns the exact object that was passed to it in the first place. As such, at runtime, there is no specialization of the generic parameter T
that can violate the cast.
Aka, you are casting an object as it's own type.
这篇关于为什么要压制这种未经检查的警告是安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!