I have a field like List<? extends MyPojo> myPojos = new ArrayList<>();
.
I want to -through reflection- get the fact that the upper bound of myPojos
is of type MyPojo
.
I can get the Field
no problem, and then getGenericType
, but that just returns a Type
which has no methods on it. I can cast it to ParameterizedType
, but getActualTypeArguments()
.
The toString()
method on the ParameterizedType
returns the expected value, there seems to be no way to access the information on the wildcard upper boud, and all the implementations of ParameterizedType
seem to be in sun.
packages.
So, can I -without parsing the toString()
output- get the upperbound of the generic type without resorting to depending on sun.*
classes? Or is this information lost due to erasure?
In generics ? (called as unbounded wildcard) is used to accept just any type of object. However, we can restrict this behaviour by applying a Lower-Bound or Upper-Bound to wildcard ?. Upper-bound is when you specify (? extends Field) means argument can be any Field or subclass of Field.
The Upper Bounded Wildcards section shows that an upper bounded wildcard restricts the unknown type to be a specific type or a subtype of that type and is represented using the extends keyword. In a similar way, a lower bounded wildcard restricts the unknown type to be a specific type or a super type of that type.
Java generics upper bounded wildcard : Upper bounded wildcard is used to restrict the unknown type to be a specific type or a subtype of that type using '? ' with extends keyword.
Guidelines for Wildcards. Upper bound wildcard − If a variable is of in category, use extends keyword with wildcard. Lower bound wildcard − If a variable is of out category, use super keyword with wildcard. Unbounded wildcard − If a variable can be accessed using Object class method then use an unbound wildcard.
You do need to cast to ParameterizedType
, and then cast the Type
values from getActualTypeArguments()
to WildcardType
, which has a getUpperBounds()
method.
So
assert MyPojo.class == ((WildcardType) ((ParameterizedType) listField.getGenericType()).getActualTypeArguments()[0]).getUpperBounds()[0];
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