Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get upperbound of wildcarded generic field?

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?

like image 445
Sled Avatar asked Jan 16 '14 22:01

Sled


People also ask

What is upper bound in generics?

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.

What is upper bound and lower bound in generics Java?

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.

What is upper bounded wildcards in generics?

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.

How do you use generic wildcards?

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.


1 Answers

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];
like image 143
Louis Wasserman Avatar answered Sep 19 '22 21:09

Louis Wasserman