Dynamic Return Type in Java method

前端 未结 5 1942
隐瞒了意图╮
隐瞒了意图╮ 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:57

    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 getSomething(...) { }
    

    or

    interface Wrapper { T getObject(); }
    
    public  Wrapper 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 {
        final byte[] bytes;
    
        Strategy(byte[] bytes) { this.bytes = bytes; }
    
        protected abstract T execute();
    }
    

    then

    class BooleanStrategy extends Strategy {
        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.

提交回复
热议问题