Java generic return type

前端 未结 4 440
迷失自我
迷失自我 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:34

    The short answer is don't. As soon as instanceof gets involved, Generics are usually the wrong answer. Use overloaded methods instead:

    public String doIt(String param){
        return "string";
    }
    
    public Integer doIt(Integer param){
        return 1;
    }
    
    public Object doIt(Object param){
        return null;
    }
    

提交回复
热议问题