Dynamic Return Type in Java method

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

    You can't do it. Java return types have to be either a fixed fundamental type or an object class. I'm pretty sure the best you can do is return a wrapper type which has methods to fetch various possible types of values, and an internal enum which says which one is valid.

    --- edit --- after Danieth's correction!

    public  Any getParam(boolean b){
    return((Any)((Boolean)(!b)));
    }
    public  Any getParam(float a) {
     return((Any)((Float)(a+1)));
    }
    public  Any getParam(Object b) {
     return((Any)b);
    }
    public void test(){
      boolean foo = getParam(true);
      float bar = getParam(1.0f);
      float mumble = getParam(this); // will get a class cast exception
    }
    

    You still incur some penalties for boxing items and type checking the returned values, and of course if your call isn't consistent with what the implementations of getParam actually do, you'll get a class cast exception.

提交回复
热议问题