0

呼び出し元にいくつかのプリミティブ データ型を返すことができる関数を作成したいと思います。

最初のプリミティブの関数結果を返すことができることは知っていますが、関数パラメーターでプリミティブを返す方法は?

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

プリミティブを返して整数やブール値などのオブジェクトにラップする唯一の方法ですか?

4

1 に答える 1

1

プリミティブを返して整数やブール値などのオブジェクトにラップする唯一の方法ですか?

全くない、

変数を Object に変換し、後でキャストまたはでフェッチすることはお勧めできませんinstanceof

  • Interface を callback として使用できます。

例:

その他のクラス

 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 に答える