Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting generic types without warning?

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.

like image 392
Jin Kwon Avatar asked Oct 03 '22 09:10

Jin Kwon


2 Answers

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...

like image 111
nkukhar Avatar answered Oct 10 '22 20:10

nkukhar


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.

like image 26
tbodt Avatar answered Oct 10 '22 19:10

tbodt