Dynamic Return Type in Java method

Jon Egeland picture Jon Egeland · Nov 19, 2011 · Viewed 47.1k times · Source

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. What I want/need to do is determine the return type by the parsed value of a byte[]. From what I've gathered, the following could work:

public Comparable getParam(String param, byte[] data) {
    if(param.equals("some boolean variable")
        return data[0] != 0;
    else(param.equals("some float variable") {
        //create a new float, f, from some 4 bytes in data
        return f;
    }
    return null;
}

I just want to make sure that this has a chance of working before I screw anything up. Thanks in advance.

Answer

hisdrewness picture hisdrewness · Nov 19, 2011

I don't know what these people are talking about. You lose type safety, which is a concern, but you could easily accomplish this with generics...something like:

public <T> T getSomething(...) { }

or

interface Wrapper<T> { T getObject(); }

public <T> Wrapper<T> getSomething(...) { }

The latter promotes the possibility of a strategy pattern. Pass the bytes to the strategy, let it execute and retrieve the output. You would have a Byte strategy, Boolean strategy, etc.

abstract class Strategy<T> {
    final byte[] bytes;

    Strategy(byte[] bytes) { this.bytes = bytes; }

    protected abstract T execute();
}

then

class BooleanStrategy extends Strategy<Boolean> {
    public BooleanStrategy(byte[] bytes) { super(bytes); }

    @Override
    public Boolean execute() {
        return bytes[0] != 0;
    }

}

Your example code is a bad use case though and I wouldn't recommend it. Your method doesn't make much sense.