I'm trying to write a method in Java that has a mixed return type (like you have in PHP).
This method is supposed take a simple user input string and, using Generics, convert it to the appropriate type and return that value.
@SuppressWarnings("unchecked")
public static <T> T askUser(String message, Class clazz) throws NumberFormatException {
// get the user input
String inputString = JOptionPane.showInputDialog(message),
className = clazz.getCanonicalName();
// return a Boolean, Integer or String
if (className.equals(Boolean.class.getCanonicalName())) {
return (T) Boolean.valueOf(inputString);
} else if (className.equals(Integer.class.getCanonicalName())) {
return (T) Integer.valueOf(inputString);
} else /*return the String*/ {
return (T) inputString;
}
}
And I'm running the code like this:
String userName = name_game.<String>askUser("Please enter your name.", String.class);
Integer userAge = name_game.<Integer>askUser("Please enter your age.", Integer.class);
tellUser("So your name is %s and your age is %d...", userName, userAge);
Boolean confirm = name_game.<Boolean>askUser("Is this correct?", Boolean.class);
tellUser("You said %b.", confirm);
But I can't figure out how to get it working without the (T) casting, and passing the Class parameter also seems as though it could be avoided.
How can I write this method without having to resort to casting to (T) ?