
Compiler warning when casting to generic method type variable in Java
By: a guest on
Feb 22nd, 2012 | syntax:
None | size: 1.37 KB | hits: 12 | expires: Never
1 import java.lang.reflect.Method;
2 import java.lang.reflect.InvocationTargetException;
3
4 public class Example
5 {
6 public static <T> void foo(Method method, String target, Object argument, T expectedReturn) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException
7 {
8 T actualReturn = (T) method.invoke(target, argument);
9 System.out.print(actualReturn.equals(expectedReturn));
10 }
11
12 public static void main(String[ ] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException
13 {
14 foo(String.class.getMethod("charAt", int.class), "test", 1, 'e');
15 }
16 }
T actualReturn = method.getReturnType( ).cast(method.invoke(target, argument));
Object actualReturn = method.invoke(target, argument);
System.out.print(actualReturn.equals(expectedReturn));
Object actualReturn = method.invoke(target, argument);
System.out.print(expectedReturn.equals(actualReturn));
public static <T> void foo(Class<T> returnType, Method method, String target, Object argument, T expectedReturn) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException
{
T actualReturn = returnType.cast(method.invoke(target, argument));
System.out.print(actualReturn.equals(expectedReturn));
}
foo(Character.class, String.class.getMethod("charAt", int.class), "test", 1, 'e');