'Using methods passed in to other methods
So in trying to create some built in error detection, I thought I might want to specify a method to be called when an error occurs. However, I am having trouble getting this to work how I want it to. What am I doing wrong / how do I pass in a method to use it in another method?
/**
* Gets the input of a user
*
* @param prompt input prompt
* @param type datatype object you want as an output
* @param errorMethod Method that executes if there is an invalid input
* @param params parameters for the errorMethod
* @return input value
*/
public static <T> T repeatedGetInput(String prompt, Class<T> type, Method errorMethod, Object... params){
Scanner scn = new Scanner(System.in);
while (true) {
System.out.print(prompt);
String input = scn.nextLine();
if (type.equals(String.class))
return type.cast(input);//String doesn't have a .valueOf(String str) so I made an edge case
try {
Method valueOf = type.getMethod("valueOf", String.class);
return type.cast(valueOf.invoke(null, input));
} catch (Exception e) {
try{
errorMethod.invoke(null, params);
ConsoleFunctions.cls();
} catch (Exception x) {
x.printStackTrace();
}
}
}
}
Invocation:
int value = ConsoleFunctions.repeatedGetInput("Enter a number: ", Integer.class, MessagePrompts.invalidInput() );
I end up getting an error saying this.
Required type Provided
type: Class<T> Class<Integer>
errorMethod :Method void
reason: void is not compatible with Method
The method declaration I am passing in looks like this, and I see that it is return type void.
public static void invalidInput( ) {
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
