Java方法中的动态返回类型 [英] Dynamic Return Type in Java method

查看:239
本文介绍了Java方法中的动态返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里遇到过这样多次的问题,但有一个很大的区别。



在其他问题中,返回类型是确定的通过参数。我想/需要做的是通过 byte [] 的解析值确定返回类型。从我收集的内容中,以下内容可以正常工作:

  public Comparable getParam(String param,byte [] data){
if(param.equals(some boolean variable)
return data [0]!= 0;
else(param.equals(some float variable){
/ /创建一个新的float,f,从数据中的大约4个字节
return f;
}
return null;
}
/ pre>

我只是想确保这有一​​个机会在我搞砸任何东西之前,谢谢提前。

解决方案

你不能这样做Java返回类型必须是一个固定的基本类型
或一个对象类,我很确定最好的可以做的是返回一个包装类型
,它具有获取各种可能类型的值的方法,以及一个内部枚举
,表示哪个有效。



---编辑---在Danieth的修正之后

  public< Any> Any getPa ram(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); //会得到一个类放映异常
}

你仍然对拳击项目施加一些惩罚并输入检查
返回的值,当然如果您的调用与
不一致,getParam的实现实际上会如何,您将得到一个
类异常。


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.

解决方案

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> Any getParam(boolean b){
return((Any)((Boolean)(!b)));
}
public <Any> Any getParam(float a) {
 return((Any)((Float)(a+1)));
}
public <Any> 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.

这篇关于Java方法中的动态返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆