Using Java Generics, I tried to implement a generic console input method.
public static <T> T readFromInput(String message, Class<?> c) throws Exception{
System.out.println(message);
Scanner scanner = new Scanner(System.in);
try {
if(c == Integer.class)
return (T) Integer.valueOf(scanner.nextInt());
if(c == String.class)
return (T) scanner.nextLine();
if(c == Double.class)
return (T) Double.valueOf(scanner.nextDouble());
if(c == Float.class)
return (T) Float.valueOf(scanner.nextFloat());
} catch (InputMismatchException e) {
throw new Exception(e);
}
return null;
}
I'm having a warning "Type safety: Unchecked cast from Integer to T". Aside from @SuppressWarnings, is it possible to avoid this warning?
Are there better ways to implement my method? Thanks in advance
You can do the following:
However, I strongly recommend not throwing Exception. Throw a more specific exception (either the original runtime exception or some appropriate checked exception).
You can get rid of the warning by using the concrete class you pass in to cast the object:
I would tempted in this case to implement multiple readFromInput methods overridden with your desired types, e.g. public static Float readFromInput(String message, Class c) public static Integer readFromInput(String message, Class c) etc.
I think you might be trying to over abstract the problem. What's wrong with just doing this?
No cast required and you still have to handle the exception either way........
Remember KISS, "Keep It Simple Stupid"...
You can use the
Class#cast
method instead, but should leave some comments, because even thoughcast
does not create a warning, it can throw a ClassCastException at runtime if the cast is not possible.Note that I've changed the method signature slightly - it should be
Class<T>
and notClass<?>
to guarantee, that theClass
instance is consistent with the type parameter.Others have shown how you can do it with
Class.cast
, but how should you do it?I suggest
readInt
,readString
,readFloat
andreadDouble
methods. Also, I suspectScanner
may buffer, which could lead you into trouble.Do it like this: