Return different type of data from a method in java?
Generally if you are not sure of what value you will end up returning, you should consider using return-type as super-class of all the return values. In this case, where you need to return String or int, consider returning Object class(which is the base class of all the classes defined in java).
But be careful to have instanceof checks where you are calling this method. Or else you may end up getting ClassCastException.
public static void main(String args[]) {
Object obj = myMethod(); // i am calling static method from main() which return Object
if(obj instanceof String){
// Do something
}else(obj instance of Integer) {
//do something else
}
I create various return types using enum. It doesn't defined automatically. That implementation look like factory pattern.
public enum SmartReturn {
IntegerType, DoubleType;
@SuppressWarnings("unchecked")
public <T> T comeback(String value) {
switch (this) {
case IntegerType:
return (T) Integer.valueOf(value);
case DoubleType:
return (T) Double.valueOf(value);
default:
return null;
}
}
}
Unit Test:
public class MultipleReturnTypeTest {
@Test
public void returnIntegerOrString() {
Assert.assertTrue(SmartReturn.IntegerType.comeback("1") instanceof Integer);
Assert.assertTrue(SmartReturn.DoubleType.comeback("1") instanceof Double);
}
}
No. Java methods can only return one result (void
, a primitive, or an object), and creating a struct
-type class like this is exactly how you do it.
As a note, it is frequently possible to make classes like your ReturningValues
immutable like this:
public class ReturningValues {
public final String value;
public final int index;
public ReturningValues(String value, int index) {
this.value = value;
this.index = index;
}
}
This has the advantage that a ReturningValues
can be passed around, such as between threads, with no concerns about accidentally getting things out of sync.