[英]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'. 我有一个类型为
Optional<String>
的对象,我想在运行时知道Optional
的通用类型是什么-意思是'String'。
I've tried: 我试过了:
obj.getClass()
but this returns java.util.Optional
但这返回
java.util.Optional
then I tried, 然后我尝试了
obj.getParameterizedType();
but this doesn't return it has Class<> object. 但这不会返回它具有Class <>对象。
Any idea?? 任何想法??
There's no such thing as an object of type Optional<String>
. 没有类型为
Optional<String>
的对象。 Type erasure means that there's just Optional
at execution time. 类型擦除意味着执行时只有
Optional
。 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. 如果您具有类型为
Optional<String>
的字段或参数,则可以在执行时检索该信息-但是对象本身不知道该信息。
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
. 基本上,这里的
Optional<>
没有什么特别的-它具有与使用List<>
...相同的局限性,尽管最后,您甚至不能使用Guava的TypeToken
类的东西所使用的任何解决方法。
See the Java Generics FAQ on Type Erasure for more details. 有关更多详细信息,请参见有关类型清除的Java泛型常见问题解答 。
As explained in the answer by Jon Skeet, you can't simply retrieve the generic type. 如Jon Skeet的答案所述,您不能简单地检索泛型。 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. 当然,当Optional为空时,这将无济于事,但在某些情况下它可以工作。
As other answers have pointed out if what you have is just the instance of the Optional object then you're out of luck. 正如其他答案所指出的那样,如果您拥有的只是Optional对象的实例,那么您就不走运了。 If, however, you have the class of the object defining the Optional property you can do something like this:
但是,如果您具有定义Optional属性的对象类,则可以执行以下操作:
Class clazz = (Class) ((ParameterizedType) MyClass.class.getDeclaredField("name-of-optional-field").getGenericType()).getActualTypeArguments()[0];
It's butt-ugly but it works. 很难看,但是可以用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.