Java generic return type

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

    if you don't want to have a specific interface to handle that stuff you can use a generic method in this way:

    public  T mymethod(T type)
    {
      return type;
    }
    

    Mind that in this way the compiler doesn't know anything about the type that you plan to use inside that method, so you should use a bound type, for example:

    public  T mymethod(T type)
    {
      // now you can use YourType methods
      return type;
    }
    

    But you should be sure that you need a generic method, that means that the implementation of doIt will be the same for all the types you are planning to use it with. Otherwise if every implementation is different just overload the methods, it will work fine since return type is not used for dynamic binding:

    public String my(String s)
    {
      return s;
    }
    
    public int my(int s)
    {
      return s;
    }
    
    int i = my(23);
    String s = my("lol");
    

提交回复
热议问题