I have an object of type: Optional<String>
and I would like to know at runtime what is the generic type of Optional
- meaning 'String'.
I've tried:
obj.getClass()
but this returns java.util.Optional
then I tried,
obj.getParameterizedType();
but this doesn't return it has Class<> object.
Any idea??
There's no such thing as an object of type Optional<String>
. Type erasure means that there's just Optional
at execution time. If you have a field or parameter of type Optional<String>
, that information can be retrieved at execution time - but the object itself doesn't know about it.
Basically, there's nothing special about Optional<>
here - it has all the same limitations as using List<>
... although as it's final, you can't even use any of the workarounds used by things like Guava's TypeToken
.
See the Java Generics FAQ on Type Erasure for more details.
See more on this question at Stackoverflow