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.
@SuppressWarnings("unchecked") is used when Java generics just don't let you do what you want to, and thus, you need to explicitly specify to the compiler that whatever you are doing is legal and can be executed at the time of execution.
Use of @SuppressWarnings is to suppress or ignore warnings coming from the compiler, i.e., the compiler will ignore warnings if any for that piece of code. 1. @SuppressWarnings("unchecked") public class Calculator { } - Here, it will ignore all unchecked warnings coming from that class.
The @SuppressWarnings annotation type allows Java programmers to disable compilation warnings for a certain part of a program (type, field, method, parameter, constructor, and local variable). Normally warnings are good. However in some cases they would be inappropriate and annoying.
If we can't eliminate the “unchecked cast” warning and we're sure that the code provoking the warning is typesafe, we can suppress the warning using the SuppressWarnings(“unchecked”) annotation. When we use the @SuppressWarning(“unchecked”) annotation, we should always put it on the smallest scope possible.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With