Java – warnings when using reflection and generics
•
Java
How can I rewrite:
<T> T callMethod(String methodName,Object[] parameters) throws ... { ... return (T) SomeClass.class.getDeclaredMethod(methodName,parameterTypes).invoke(binding,parameters); }
So it doesn't generate a warning
warning: [unchecked] unchecked cast return (T) SomeClass.class.getDeclaredMethod(methodName,parameters); required: T found: Object where T is a type-variable: T extends Object declared in method <T>callMethod(String,Object[])
I mean, no supresswarnings solution
Solution
As Peter Lawley pointed out:
I will go further and say that callmethod should not be a general method at all Since the caller determines which method to call by passing its name as a string, the method should only return object - just like the call - and force the call site
Don't use @ suppresswarnings – there's no way to prove it here
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码