Java generic return tpye
Posted
by Colby77
on Stack Overflow
See other posts from Stack Overflow
or by Colby77
Published on 2010-04-19T17:01:45Z
Indexed on
2010/04/19
17:03 UTC
Read the original article
Hit count: 229
Hi,
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?
© Stack Overflow or respective owner