Would there be a better way to write this getInput() method instead of checking for every single class that could be passed in?
public Object getInput(String prompt, Class<?> type) {
System.out.print(prompt);
Scanner scn = new Scanner( System.in );
String str = scn.nextLine( );
if(type.equals(Integer.class))
return Integer.parseInt(str);
else if (type.equals(Double.class))
return Double.parseDouble(str);
else if (type.equals(Boolean.class))
return Boolean.parseBoolean(str);
else return type.cast(str);
}
It works enough, but I would like to make it work with mostly all cases without having to add many more else if statements. As well as this, I am required to cast to that type when I take the input and assign it to a variable. Is there a way I could get around this?
Invocation:
int num = (int)menu.getInput("Enter an integer: ", Integer.class);
Maybe you can try to use reflection since these classes(Integer
, Boolean
...) usually have a static valueOf
method:
public static void main(String[] args) {
int input = getInput("1", Integer.class);
System.out.println(input);
}
public static <T> T getInput(String input, Class<T> type) {
try {
Method valueOf = type.getMethod("valueOf", String.class);
return type.cast(valueOf.invoke(null, input));
} catch (Exception e) {
return null;
}
}