Java Reference
In-Depth Information
rayType
object whose
getComponentType
would return a
ParameterizedType
for
List<String>
.
[4]
You may recall that you cannot create such an array, but you are permitted to declare variables
of that type. The actual array creation can use only an unbounded wildcard type, such as
new
List<?>[1]
. When you first assign the new array to a more specific variable, such as a
List<String>[]
, you will get an "unchecked" warning because the compiler cannot guarantee that the
current or future contents of the array will actually be
List<String>
objects. Such arrays are inherently
unsafe and should be used with extreme cautionyou should generally not create methods that return
such arrays or take them as parameters.
The component type object gets created when
getGenericComponentType
is
invoked, so as you might expect, you may get a
TypeNotPresentException
or
MalformedParameterizedTypeException
.
16.9.5. String Representations of Type Objects
None of the interfaces described above define the
toString
method, or
any other general way to obtain a string representation of a typewith
the exception of
TypeVariable
, which has the
getName
method. However,
all the type objects will have a
toString
method defined. With no spe-
cification of what
toString
should return for
Type
objects, you cannot rely
on
toString
to give a reasonable representation of the type. If you want
a string representation of a type, you will need to assemble it yourself
from the information available. For example, if a
WildcardType
object has
no lower bound and an upper bound of
X
, then the wildcard is "
?extends
X
". For a
ParameterizedType
you can construct the string representation
using the raw type and the actual type parameter types.
Exercise 16.9
: Use reflection to write a program that will print a full de-
claration of a named class, including everything except the import state-
ments, comments, and code for initializers, constructors, and methods.
The member declarations should appear just as you would write them.
You will need to use all the reflection classes you have seen. Also note
that the
toString
methods of many of the reflection objects will not
provide the information you want in the correct format, so you will need
to piece together the individual pieces of information.