Edit: I initially accepted the answer, but I was not very happy with this, since I wanted to use generics correctly. So, I continued to do research and found a solution. Read about it in my answer below.
Here is a bit of a self-contained piece of Java code that shows what I'm trying to do. It compiles, runs, and behaves correctly.
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 }
Running this fingerprint true on the console, as I expected. What bothers me is because on line 8 I get a warning when I compile it as shown below (jGRASP is my IDE, by the way).
---- jGRASP exec: javac -g -Xlint: unchecked Sandbox.java
Sandbox.java:8: warning: [unchecked] unchecked cast
found: java.lang.Object
required: T 1 warning
---- jGRASP: operation completed.
I initially tried line 8 without a cast, but this could not be compiled with an error complaining about finding Object when T is required ( invoke returns Object ). Later I rewrote it like this, blindly hoping to get rid of the warning.
T actualReturn = method.getReturnType( ).cast(method.invoke(target, argument));
But this gives a compilation error, due to which I can not make the head and tail.
---- jGRASP exec: javac -g -Xlint: unchecked Sandbox.java
Sandbox.java:8: incompatible types
found: capture # 898 of
required: T 1 error
---- jGRASP wedge: exit code for the process is 1.
---- jGRASP: job completed.
And this number next to capture# is different every time I try to compile the same line of code.
So what is the problem? Why do I get a warning when I return the object returned by calling a type variable? Does this mean that I am doing something wrong? How can I write this so that the warning disappears? And I would rather not overwhelm it with an annotation, since it does not seem to solve many problems.