When I read Effective Java item 27, the type casting between UnaryFunction<Object>
and UnaryFunction<T>
confused me.
interface UnaryFunction<T> {
T apply(T t);
}
public class Main {
private static final UnaryFunction<Object> IDENTITY = new UnaryFunction<Object>() {
public Object apply(Object t) {
return t;
}
};
@SuppressWarnings("unchecked")
public static <T> UnaryFunction<T> identityFunction() {
return (UnaryFunction<T>) IDENTITY;
}
public static void main(String ... args) {
UnaryFunction<A> identityA = Main.identityFunction();
A a = identityA.apply(new A());
}
}
class A {}
Why UnaryFunction<Object>
can be casted to UnaryFunction<T>
?
I know the generic type will be erased after complier. So (UnaryFunction<T>) IDENTITY
will eventually be (UnaryFunction<Object>) IDENTITY
, this will be working in Runtime.
But directly casting UnaryFunction<Object>
to UnaryFunction<A>
is not allowed by compiler.
UnaryFunction<A> identityA = (UnaryFunction<A>)IDENTITY;
//incompatible types: UnaryFunction<java.lang.Object> cannot be converted to UnaryFunction<A>
And there is no inheritance relationship between UnaryFunction<Object>
and UnaryFunction<T>
. So why UnaryFunction<Object>
can be casted to UnaryFunction<T>
?