0

我想做一个可以向调用者返回几种原始数据类型的函数。

我知道我可以返回第一个原语的函数结果,但是如何在函数参数中返回原语?

public boolean myFunc( boolean outAnotherPrimitive)
{
outAnotherPrimitive = true; //need to return value to caller
return true;
}

它是返回原语以将其包装成像整数或布尔值这样的对象的唯一方法吗?

4

1 回答 1

1

它是返回原语以将其包装成像整数或布尔值这样的对象的唯一方法吗?

一点也不,

我认为将变量转换为 Object 并在使用 cast 或instanceof.

  • 您可以使用接口作为回调

例子:

其他类

 public class OtherClass{

....

public void myFunc( boolean anotherPrimitive, MyinterfaceItf myItf)
{
 boolean bool = false;
 int a = 1; 
  myItf.onFinish(bool, a)
}
....
}

我的课:

public class MyClass implements MyinterfaceItf {

 ....

 private void foo()
 {
    MyinterfaceItf itf = this;

    myFunc(true, itf );
 }

 @override
 public void onFinish(bool, a){
   // here you can get your primitive data 
 }

}

界面

public interface MyinterfaceItf{
 public void onFinish(bool, a);
} 
  • 将变量用作全局变量的其他选项

例子:

private boolean bool = false;
private int num = 0;


public boolean myFunc( boolean anotherPrimitive)
{
 bool = anotherPrimitive;
 num = 10;
 //....
}
  • 下一个创建新类并使用它代替原语的选项。

例子:

public class NewClass{
 private boolean bool = false;
 private int num = 0;
 //...

 public void setBool(boolean flag){
     this.bool = flag;
  }
}

 public boolean myFunc( boolean anotherPrimitive, NewClass newClass)
 {
   return newClass.setBool(true);
  }

(我在本地编辑器中写的,对不起语法)

于 2013-09-25T16:06:32.817 回答