Improvement/s to my Java generic console input met

2019-02-17 17:45发布

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

8条回答
不美不萌又怎样
2楼-- · 2019-02-17 18:07

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.

查看更多
Lonely孤独者°
3楼-- · 2019-02-17 18:14

Reading from this post, Java generic function: how to return Generic type I got rid of my warning:

public static <T> T readFromInput(String message, Class<T> c) throws Exception{
        System.out.println(message);
        Scanner scanner = new Scanner(System.in);
        try {
            if(c == Integer.class)
                return c.cast(scanner.nextInt());
            if(c == String.class)
                return c.cast(scanner.nextLine());
            if(c == Double.class)
                return c.cast(scanner.nextDouble());
            if(c == Float.class)
                return c.cast(scanner.nextFloat());
        } catch (InputMismatchException e) {
            throw new Exception(e);
        }
        return null;
    }
查看更多
登录 后发表回答