Java通用返回类型 [英] Java generic return type
问题描述
我想写一个方法可以接受一个类型参数(或任何方法可以从中找出类型)并返回这个类型的值,所以我不需要强制返回类型。 p>
以下是一个方法:
public Object doIt(Object param){
if(param instanceof String){
returnstring;
} else if(param instanceof Integer){
return 1;
} else {
return null;
当我调用这个方法时,字符串,即使我知道返回类型将是一个字符串,我必须施放返回对象。这与int参数类似。
我该如何编写这个方法来接受一个类型参数,并返回这个类型?
public< T> T mymethod(T型)
{
返回类型;
$ / code>
请注意,通过这种方式,编译器不知道类型您打算在该方法中使用,所以您应该使用绑定类型,例如:
public< T extends YourType> T mymethod(T型)
{
//现在你可以使用YourType方法
返回类型;
}
但是你应该确定你需要一个通用的方法,这意味着对于您计划使用的所有类型, doIt
的实现将相同。否则,如果每个实现不同,只是重载方法,它将工作正常,因为返回类型不用于动态绑定:
public String my(String s)
{
return s;
}
public int my(int s)
{
return s;
}
int i = my(23);
String s = my(lol);
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> 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 extends YourType> 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");
这篇关于Java通用返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!