我想创建可以向调用者返回几种原始数据类型的函数。
我知道我可以返回第一个原语的函数结果,但是如何在函数参数中返回原语?
public boolean myFunc( boolean outAnotherPrimitive)
{
outAnotherPrimitive = true; //need to return value to caller
return true;
}
是否只返回原语以将其包装为Integer或Boolean等对象?
答案 0 :(得分:1)
是否只返回原语以将其包装为Integer或Boolean等对象?
完全没有,
我认为将变量转换为Object并在使用强制转换或instanceof
获取它们之后,这不是一个好习惯。
示例:
<强> OtherClass 强>
public class OtherClass{
....
public void myFunc( boolean anotherPrimitive, MyinterfaceItf myItf)
{
boolean bool = false;
int a = 1;
myItf.onFinish(bool, a)
}
....
}
<强> MyClass的:强>
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);
}
(我在本地编辑中写道,对不起语法)