我简化了我的代码如下:重构通过传递泛型方法
static private String waitForString(String expected, int attempts) {
String actual = null;
for (int i = 0; i < attempts; i++){
actual = getString();
if (validateString(actual, expected)) {
return actual;
}
}
return null;
}
static private int waitForInt(int expected, int attempts) {
int actual = 0;
for (int i = 0; i < attempts; i++){
actual = getInt();
if (validateInt(actual, expected)) {
return actual;
}
}
return 0;
}
由于我使用的是同一回路(因为我有不止一个相应的“吸气剂”的方法不止一个类和验证方法)我想重构它。我尝试这样做:
static <T> T helperMethod(Method getMethod, Method validator,T expected, int attempts) {
T actual = null;
for (int i = 0; i < attempts; i++){
actual = method.invoke(null);
if (validator.invoke(null, actual, expected)) {
return actual;
}
}
return null;
}
但是我得到以下错误:
actual = method.invoke(null);
error: incompatible types: Object cannot be converted to T
validator.invoke(null, actual, expected)
error: incompatible types: Object cannot be converted to boolean
我可以在函数声明中指定只接受正确的返回类型的方法?如果是这样,怎么样? 其他重构方式的想法将不胜感激。
EDITED 为了说清楚,我没有问如何反映该方法的返回类型。 谢谢你VGR的解决方案。
可能重复的[如何在JAVA中找到返回类型的方法?](http://stackoverflow.com/questions/14730223/how-to-find-return-type-of-a-method-in -java) –
@DmytroGrynets这与OP问题意味着什么? –
他可以在他的方法中找到方法的返回类型并检查它 –