从java中的方法返回不同类型的数据?

Ruc*_*era 28 java return return-type

public static void main(String args[]) {
    myMethod(); // i am calling static method from main()
 }
Run Code Online (Sandbox Code Playgroud)

.

public static ? myMethod(){ // ? = what should be the return type
    return value;// is String
    return index;// is int
}
Run Code Online (Sandbox Code Playgroud)

myMethod()将返回String和int值.所以从main()我拿出这些返回值得出以下解决方案.

创建一个类调用 ReturningValues

public class ReturningValues {
private String value;
private int index;

// getters and setters here
}
Run Code Online (Sandbox Code Playgroud)

并改变myMethod()如下.

 public static ReturningValues myMethod() {
    ReturningValues rv = new ReturningValues();
    rv.setValue("value");
    rv.setIndex(12);
    return rv;
}
Run Code Online (Sandbox Code Playgroud)

现在我的问题是,有没有更简单的方法来实现这一点?

Wen*_*del 21

我使用枚举创建各种返回类型.它没有自动定义.该实现看起来像工厂模式.

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

单元测试:

public class MultipleReturnTypeTest {

  @Test
  public void returnIntegerOrString() {
     Assert.assertTrue(SmartReturn.IntegerType.comeback("1") instanceof Integer);
     Assert.assertTrue(SmartReturn.DoubleType.comeback("1") instanceof Double);
  }

}
Run Code Online (Sandbox Code Playgroud)

  • 我个人认为使用枚举之类的方法看起来很奇怪。更像是骇客。 (2认同)

chr*_*ke- 17

不可以.Java方法只能返回一个结果(void,一个原语或一个对象),而创建一个struct像这样的-type类正是你这样做的.

作为一个注释,经常有可能像你ReturningValues这样的类不可变类:

public class ReturningValues {
    public final String value;
    public final int index;

    public ReturningValues(String value, int index) {
        this.value = value;
        this.index = index;
    }
}
Run Code Online (Sandbox Code Playgroud)

这样做的优点是ReturningValues可以传递a ,例如线程之间,而不用担心意外地使事情不同步.


Ank*_*hag 6

通常,如果您不确定最终返回的值是什么,则应考虑使用return-type作为所有返回值的超类.在这种情况下,您需要返回String或int,请考虑返回Object类(它是java中定义的所有类的基类).

但是要小心在您调用此方法的地方进行instanceof检查.否则你可能最终得到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
     }
Run Code Online (Sandbox Code Playgroud)


Ruc*_*era 0

最后,我认为我的方法更好,因为当返回类型的数量增加时,这种实现会以最好的方式做到这一点。

public static ReturningValues myMethod() {
ReturningValues rv = new ReturningValues();
rv.setValue("value");
rv.setIndex(12);
return rv;
}
Run Code Online (Sandbox Code Playgroud)