在参数Java访问变量 [英] Java access variables in arguments
问题描述
我想能够访问传递给我的方法的变量。我知道的C可能有某种方式来东西的地址作为参数传递,则指的是作为一个指针,并能够使用变量。总之,这里是一个例子。
无效myFunction的(地址变量){
*变量=榜样;
}
然后调用它为:
myFunction的(安培; somevariable);
有没有办法通过引用或Java中的指针传递参数,从而达到您想要的传递效果的唯一途径的可变的对象,并改变它,你调用方法中值:
公共类ChangeableInt {
私人诠释数目;
公共ChangeableInt(int值){数=值;}
公众诠释的get(){返回号码;}
公共无效集(int值){数=值;}
}
使用这个类在手,你可以这样做:
无效myFunction的(ChangeableInt ARG){
arg.set(42);
}
...
ChangeableInt VAL =新ChangeableInt(123);
myFunction的(VAL);
的System.out.println(val.get()); //输出42
I would like to be able to access a variable passed to my method. I know C might have has some kind of way to pass the address of something as an argument, then refer to that as a pointer and be able to use the variable. Anyway, here's an example.
void myFunction(address to variable) {
*variable = "example";
}
Then call it as:
myFunction(&somevariable);
There is no way to pass arguments by reference or by pointer in Java, so the only way to achieve the effect that you would like is passing a mutable object, and changing its value inside the method that you call:
public class ChangeableInt {
private int number;
public ChangeableInt(int value) {number = value;}
public int get() {return number;}
public void set(int value) {number = value;}
}
With this class in hand, you can do this:
void myFunction(ChangeableInt arg) {
arg.set(42);
}
...
ChangeableInt val = new ChangeableInt(123);
myFunction(val);
System.out.println(val.get()); // prints 42
这篇关于在参数Java访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!