问题描述
考虑 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
函数?
只有当身份函数首先返回传递给它的 精确 对象时,演员才是安全的。因此,在运行时,通用参数 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 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.
这篇关于为什么要压制这种未经检查的警告是安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!