简体   繁体   中英

Java8: How to get the internal Type of java.util.Optional class?

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.

As explained in the answer by Jon Skeet, you can't simply retrieve the generic type. One workaround might be something like this:

Class<?> type = null;
if(optional.isPresent()) {
    type = optional.get().getClass();
}

Of course, this won't help when the Optional is empty but for some situations it can work.

As other answers have pointed out if what you have is just the instance of the Optional object then you're out of luck. If, however, you have the class of the object defining the Optional property you can do something like this:

Class clazz = (Class) ((ParameterizedType) MyClass.class.getDeclaredField("name-of-optional-field").getGenericType()).getActualTypeArguments()[0];

It's butt-ugly but it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM