java 函数参数传递解释
起因:
写android的程序时,要写一大堆赋值
txtYaw = (TextView)findViewById(R.id.txtYaw);
txtPitch = (TextView)findViewById(R.id.txtPitch);
txtRoll = (TextView)findViewById(R.id.txtRoll);
于是将 (TextView)findViewById封装为函数:
private void setTextViewID(TextView tv,int id)
{
tv = (TextView)findViewById(id);
}
setTextViewID(RVP,R.id.RVP);
看起来更整洁,但是发现在RVP.seText报错:
E/AndroidRuntime﹕ FATAL EXCEPTION: main java.lang.NullPointerException
发现RVP为null
于是恶补了以下java 函数参数,以“java 函数 参数 传递“为关键字搜索,发现讲的不清不出,还是搜了stack overflow
http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value
以下为主要内容:
Java is always pass-by-value. The difficult thing to understand is that Java passes objects as references and those references are passed by value.
我的理解:java 函数 参数 传递对象时,函数内部可以修改对象的属性,但是重新给对象的引用赋值不行,因为引用本身为传值。
It goes like this:
public static void main( String[] args ){
Dog aDog = new Dog("Max");
foo(aDog);
if( aDog.getName().equals("Max") ){ //true
System.out.println( "Java passes by value." );
}else if( aDog.getName().equals("Fifi") ){
System.out.println( "Java passes by reference." );
}
}
public static void foo(Dog d) {
d.getName().equals("Max"); // true
d = new Dog("Fifi");
d.getName().equals("Fifi"); // true
}
In this example aDog.getName()
will still return "Max"
. The value
aDog
within main
is not overwritten in the function
foo
with the Dog
"Fifi"
as the object reference is passed by value. If it were passed by reference, then the
aDog.getName()
in main
would return "Fifi"
after the call to
foo
.
Likewise:
Dog aDog = new Dog("Max");
foo(aDog);
aDog.getName().equals("Fifi"); // true
public void foo(Dog d) {
d.getName().equals("Max"); // true
d.setName("Fifi");
}
再有就是传递数组也是同样道理:数组内部可以修改,new一个新的数组不行
public class ArrayPar
{
public static void main(String [] args)
{
int x=1;
int y[]={1,2,3};
changeValue(x,y);
System.out.println("outside changeValue x="+x+",y[0]="+y[0]);
changeRef(y);
System.out.println("Outside changeRef y[0]="+y[0]);
}
public static void changeValue(int num,int [] array)
{
num=100;
array[0]=100;
}
public static void changeRef(int [] array)
{
array = new int[3];
array[0] = 123;
System.out.println("inside changeRef array[0]="+array[0]);
}
}
结果:
java ArrayPar
outside changeValue x=1,y[0]=100
inside changeRef array[0]=123
Outside changeRef y[0]=100//不变
回到最初的问题,java缺少宏 或者 inline等 文本替换的方式
变通策略可以采用 Sting to code 的方式,不过代价比较高,得不偿失
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。