java方法返回"多值"方案

java 并不支持多值的返回,但能够利用java一些特性来模拟。实例代码以下: java

/**
 * Created by wens on 15-5-23.
 */
public class TupleN {

    private Object[] values ;

    public TupleN(Object...values){
        this.values  = values ;
    }

    public <T> T getN(int index ){
        if(index < 0 || index >= values.length ){
            throw new IndexOutOfBoundsException(index+" of out of "+values.length) ;
        }
        return (T)values[index];
    }

    public static void main(String[] args) {
        TupleN tuple = returnMultiValue();
        String string = tuple.getN(0);
        int intV = tuple.getN(1);
        Bean b = tuple.getN(2) ;

    }


    public static TupleN returnMultiValue(){
        return new TupleN("test string" , 44, new Bean() ) ;
    }

    static class Bean {

    }

}



使用tuple对象装载返回值, tuple同时提供取出值方法(getN),结合java泛型及类型推导就不须要显式类型转换。
相关文章
相关标签/搜索