Casting generic types without warning?

I have a long history.

java generics bounds type

generics ad to reflect

Anyway, I have a method that calls a method using reflection and returns a common result.

public static <V> JAXBElement<V> unmarshal(..., Class<V> valueType); 

The problem (?) Occurs when I get the result of a method call. I have to drop it.

 final Object result = method.invoke(...); 

I found that I can use result in JAXBElement<V> as follows.

 @SuppressWarnings("unchecked") final JAXBElement<V> result = (JAXBElement<V>) method.invoke(...); return result; 

Is there any other way to do this? I mean, I used Class<V> valueType .

If not, is the following statement a 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.

+4
source share
3 answers

No, method.invoke(...) not a generic method, not even the whole Method class is generic. That way, it returns Object as the result, and you need to throw it.

 // no warning, huh? :) final JAXBElement<?> result = ... 

Yes, no warnings, but JAXBElement<?> Contains some restrictions, for example, you cannot put values ​​in this data structure. You can just get Objects from there, so you probably need to use it later in your code ...

+2
source

You need to declare a generic type V in your method as follows:

 public <V> JAXBElement<V> unmarshal(..., Class<V> valueType) 

Other than that, I cannot find errors in your code.

+1
source

In general, the short answer is no.

However, if you think about it, what would you like to achieve? You said you want to call a piece of code through reflection. Generics are used to validate code at compile time (therefore, erased at compile time and are generally not available at run time).

If you call a method by reflection, you can literally call it any type and get any type of result. It would be very difficult to prove the correctness at compile time.

Perhaps you can change your code so that it does not use reflection, and thus avoid casting.

+1
source

Source: https://habr.com/ru/post/1494254/


All Articles