I have a long story.
java generics bounds type
generics type declaration for reflection
Anyway, I have a method which invokes a method using reflection and returns a generic result.
public static <V> JAXBElement<V> unmarshal(..., Class<V> valueType);
The problem(?) is when I got the result of method invocation. I have to cast it.
final Object result = method.invoke(...);
I found I can cast the result into JAXBElement<V> like this.
@SuppressWarnings("unchecked")
final JAXBElement<V> result = (JAXBElement<V>) method.invoke(...);
return result;
Is there other way to do this? I mean I got the Class<V> valueType to use.
If not, is following statement a little bit cumbersome?
// no warning, huh? :)
final JAXBElement<?> result = (JAXBElement<?>) method.invoke(...);
return new JAXBElement<V>(result.getName(), valueType, result.getScope(),
valueType.cast(result.getValue()));
Thanks.
No, method.invoke(...) is not a generic method even entire Method class is not generic. So it returns Object as result and you have to cast.
// no warning, huh? :)
final JAXBElement<?> result = ...
Yes no warnings but JAXBElement<?> puts some restrictions, for instance you cannot put values to this data structure. You can just get Objects from there, so you probably will need to canst it later in you code...
You need to declare the generic type V in your method like this:
public <V> JAXBElement<V> unmarshal(..., Class<V> valueType)
Other than that, I can't find any mistakes in your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With