Here is a paraphrasing of a question I posed to a group of students, and it turns out that finding an answer is a bit trickier (for me, anyway) than I expected:
Suppose you have asked me to write a method, f, that has a String parameter, and returns a double. You now wish to test whether I have done my job correctly by writing your own test code that will compile if I have written f as specified, but won't compile if I have not.
Some students proposed this incorrect solution:
System.out.println(f("cat"));
This is not a good tester because it does not test the return type of the method. That is, it will compile even if I had written f to return a String or an int or a boolean, and so on.
I proposed this solution to the students:
double d = f("cat");
I reasoned that this tests whether f accepts Strings and returns doubles. But really, this is no good either. f could return an int (or any "narrower" primitive data type), and the result could be stored in d.
So, I'm seeking ideas for a simple solution (one or two lines of code, perhaps?) to the problem: write code that will compile if f has been defined correctly (String parameter, double return), but won't compile if f has not been written as specified.
Reflection is the best fit here in general (it's a pretty unusual requirement) but something else that would at least work would be to use overload resolution: provide alternative methods with a parameter of float
, long
and Double
, but with void
return types... and one with a method with a parameter of type double
and a non-void return type. Then check that you can assign a value to the result of calling that method with the result of f
. For example:
public void foo(long x) {}
public void foo(float x) {}
public void foo(Double x) {}
public void foo(Object x) {}
public int foo(double x) {
return 0;
}
// This will only compile if f is declared to return double
int check = foo(f("cat"));
See more on this question at Stackoverflow