Thursday, 22 August 2013

How to get the compiler to disallow method invocation on upper-bound reference

How to get the compiler to disallow method invocation on upper-bound
reference

I know that the following syntax is not legal:
void dolist2(List<? extends Number> list) {
list.add(new Integer(3));
}
But I do not know how the compiler knows it is not legal. If I look at the
source code of List.java I see:
boolean add(E e);
I see nothing special at all about this declaration, not even an
annotation like @IllegalWhenInvokedOnUpperBoundReference. How does the
compiler know to enforce this restriction? How do I place similar
restrictions on my own classes?

No comments:

Post a Comment