Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Compiler warning when casting to generic method type variable in Java

By: a guest on Feb 22nd, 2012  |  syntax: None  |  size: 1.37 KB  |  views: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. 1 import java.lang.reflect.Method;
  2.  2 import java.lang.reflect.InvocationTargetException;
  3.  3
  4.  4 public class Example
  5.  5 {
  6.  6    public static <T> void foo(Method method, String target, Object argument, T expectedReturn) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException
  7.  7    {
  8.  8       T actualReturn = (T) method.invoke(target, argument);
  9.  9       System.out.print(actualReturn.equals(expectedReturn));
  10. 10    }
  11. 11    
  12. 12    public static void main(String[ ] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException
  13. 13    {
  14. 14       foo(String.class.getMethod("charAt", int.class), "test", 1, 'e');
  15. 15    }
  16. 16 }
  17.        
  18. T actualReturn = method.getReturnType( ).cast(method.invoke(target, argument));
  19.        
  20. Object actualReturn = method.invoke(target, argument);
  21. System.out.print(actualReturn.equals(expectedReturn));
  22.        
  23. Object actualReturn = method.invoke(target, argument);
  24. System.out.print(expectedReturn.equals(actualReturn));
  25.        
  26. public static <T> void foo(Class<T> returnType, Method method, String target, Object argument, T expectedReturn) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException
  27. {
  28.     T actualReturn = returnType.cast(method.invoke(target, argument));
  29.     System.out.print(actualReturn.equals(expectedReturn));
  30. }
  31.        
  32. foo(Character.class, String.class.getMethod("charAt", int.class), "test", 1, 'e');
clone this paste RAW Paste Data