java 返回类型 t,Java通用返回类型

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 return type.

Here is a method:

public Object doIt(Object param){

if(param instanceof String){

return "string";

}else if(param instanceof Integer){

return 1;

}else{

return null;

}

}

When I call this method, and pass in it a String, even if I know the return type will be a String I have to cast the return Object. This is similar to the int param.

How shall I write this method to accept a type param, and return this type?

解决方案

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");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值