Java Reference
In-Depth Information
Even though a type parameter is used in the definition of the method, the class it is
defined in need not be generic—instead, the syntax is used to indicate that the
method can be used freely, and that the return type is the same as the argument.
Using and Designing Generic Types
When working with Java's generics, it can sometimes be helpful to think in terms of
two different levels of understanding:
A practitioner needs to use existing generic libraries, and to build some fairly
simple generic classes. At this level, the developer should also understand the
basics of type erasure, as several Java syntax features are confusing without at
least an awareness of the runtime handling of generics.
The designer of new libraries that use generics needs to understand much more
of the capabilities of generics. There are some nastier parts of the spec—includ‐
ing a full understanding of wildcards, and advanced topics such as “capture-of ”
error messages.
Java generics are one of the most complex parts of the language specification with a
lot of potential corner cases, which not every developer needs to fully understand, at
least on a first encounter with this part of Java's type system.
Compile and Runtime Typing
Consider an example piee>ce of code:
List < String > l = new ArrayList <>();
System . out . println ( l );
We can ask the following question: what is the type of l ? The answer to that ques‐
tion depends on whether we consider l at compile time (i.e., the type seen by javac )
or at runtime (as seen by the JVM).
javac will see the type of l as List-of-String , and will use that type information to
carefully check for syntax errors, such as an attempted add() of an illegal type.
Conversely, the JVM will see l as an object of type ArrayList —as we can see from
the println() statement. The runtime type of l is a raw type due to type erasure.
The compile-time and runtime types are therefore slightly different to each other.
The slightly strange thing is that in some ways, the runtime type is both more and
less specific than the compile-time type.
Search WWH ::

Custom Search