I have simplified my code to this:
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;
}
Since I'm using the same loop (and since I have more than one class with more than one corresponding "getter" method and validation method) I would like to refactor it. I tried this:
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;
}
However I'm getting following errors:
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
Can I specify in the function declaration only to accept methods with the correct return type? If so, how? Ideas for other ways to refactor will be appreciated.
Aucun commentaire:
Enregistrer un commentaire