Dynamic Return Type in Java method

前端 未结 5 1938
隐瞒了意图╮
隐瞒了意图╮ 2021-02-02 14:20

I\'ve seen a question similar to this multiple times here, but there is one big difference.

In the other questions, the return type is to be determined by the parameter.

5条回答
  •  别那么骄傲
    2021-02-02 14:48

    This CAN be done. The following code will work:

    public byte BOOLEAN = 1;
    public byte FLOAT = 2;
    public static  Any getParam(byte[] data) {
        if (data[0] == BOOLEAN) {
            return (Any)((Boolean)(boolean)(data[1] != 0));
        } else if (data[0] == FLOAT) {
            return (Any)((Float)(float)data[1]);
        } else {
            return null;
        }
    }
    

    By using a generic for the return type any Java method can dynamically return any object or primitive types. You can name the generic whatever you want, and in this case I called it 'Any'. Using this code you avoid casting the return type when the method is called. You would use the method like so:

    byte[] data = new byte[] { 1, 5 };
    boolean b = getParam(data);
    data = new byte[] { 2, 5 };
    float f = getParam(data);
    

    The best you can do without this trick is manually casting an Object:

    float f = (float)getParam(data);
    

    Java dynamic return types can reduce boilerplate code.

提交回复
热议问题