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
There's no general way to avoid "Unchecked cast" warning other than using
@SuppressWarnings (unchecked)
annotation.In particular case you get this warning because there's no warranty that parameter
Class<?> c
may be cast to T since Java's generics are checked only in compilation and no checks may be done in runtime.Reading from this post, Java generic function: how to return Generic type I got rid of my warning: