![](/img/trans.png)
[英]A reference to primitive type in Java (How to force a primitive data to remain boxed)
[英]Primitive data type reference
我想做一個可以將幾種原始數據類型返回給調用者的函數。
我知道我可以為第一個原語返回函數結果,但是如何在函數param中返回原語?
public boolean myFunc( boolean outAnotherPrimitive)
{
outAnotherPrimitive = true; //need to return value to caller
return true;
}
是返回原語將其包裝到Integer或Boolean之類的對象的唯一方法嗎?
是返回原語將其包裝到Integer或Boolean之類的對象的唯一方法嗎?
一點也不,
我認為將變量轉換為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);
}
(我是在本地編輯器中編寫的,語法很抱歉)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.