Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning while using reflection and generics

How do I rewrite this:

<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, parameterTypes).invoke(binding, parameters);
required: T
found:    Object
where T is a type-variable:
T extends Object declared in method <T>callMethod(String,Object[])

I mean the no-SupressWarnings solution.

like image 313
Raidmaster Avatar asked Feb 27 '26 11:02

Raidmaster


1 Answers

I think you'll have to live with the @SuppressWarnings(...) approach since the invoke() method returns an Object. Remember that generics are erased at runtime, and reflection happens at runtime...

Cheers,

like image 175
Anders R. Bystrup Avatar answered Mar 01 '26 23:03

Anders R. Bystrup