Jin*_*won 5 java generics reflection jaxb
我有一个长话。
无论如何,我有一个使用反射调用方法并返回通用结果的方法。
public static <V> JAXBElement<V> unmarshal(..., Class<V> valueType);
Run Code Online (Sandbox Code Playgroud)
问题(?)是当我得到方法调用的结果时。我必须抛弃它。
final Object result = method.invoke(...);
Run Code Online (Sandbox Code Playgroud)
我发现我可以投中result成JAXBElement<V>这个样子。
final Object result = method.invoke(...);
Run Code Online (Sandbox Code Playgroud)
还有其他方法吗?我的意思是我Class<V> valueType可以使用了。
如果不是,以下陈述是否有点cumbersome?
@SuppressWarnings("unchecked")
final JAXBElement<V> result = (JAXBElement<V>) method.invoke(...);
return result;
Run Code Online (Sandbox Code Playgroud)
谢谢。
不,method.invoke(...)即使整个类都不是通用的,也不是通用方法Method。所以它会Object作为结果返回,你必须进行强制转换。
// no warning, huh? :)
final JAXBElement<?> result = ...
Run Code Online (Sandbox Code Playgroud)
是的,没有警告,但JAXBElement<?>有一些限制,例如您不能向此数据结构添加值。您可以从那里获取Objects,因此您可能需要稍后在代码中添加它......