Java generic return type

前端 未结 4 442
迷失自我
迷失自我 2020-12-05 00:05

I\'d like to write a method that can accept a type param (or whatever the method can figure out the type from) and return a value of this type so I don\'t have to cast the r

4条回答
  •  时光说笑
    2020-12-05 00:35

    I would urge you to NOT use instanceof, however this code does what you want:

    public class Main
    {
        public static void main(String[] args) 
        {
            final Main main;
            final String strVal;
            final Integer intVal;
            final Float   floatVal;
    
            main     = new Main();
            strVal   = main.doIt("Hello");
            intVal   = main.doIt(5);
            floatVal = main.doIt(5.0f);
    
            System.out.println(strVal);
            System.out.println(intVal);
            System.out.println(floatVal);
        }
    
        public  T doIt(final T thing)
        {
            T t;
    
            if(thing instanceof String)
            {
                t = (T)"String";
            }
            else if (thing instanceof Integer)
            {
                t = (T)Integer.valueOf(1);
            }
            else
            {
                t = null;
            }
    
            return (t);
        }
    }
    

提交回复
热议问题