Java 中的“ByRef”相当于什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18105276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the equivalent to "ByRef" in Java?
提问by nick
I'm working on translating some code from VisualBasic to Java and I've encountered a snag when using the ByRef keyword in VB. That doesn't exist in Java!
我正在将一些代码从 VisualBasic 翻译成 Java,但在 VB 中使用 ByRef 关键字时遇到了障碍。这在Java中不存在!
How should I simulate a ByRef call in Java?
我应该如何在 Java 中模拟 ByRef 调用?
Edit: Just to clarify for those who don't know VB, ByRef identifies a variable in the parenthesis after calling a function and makes it so that when that variable is changes inside of the function, it will also change higher up where it is called as opposed to ByVal where only the value of the variable is remembered. Changing a ByVal variable in the method will not affect the variable where it is called.
编辑:只是为了向那些不了解 VB 的人澄清,ByRef 在调用函数后识别括号中的一个变量,并使其在函数内部发生变化时,它也会在调用它的地方发生更高的变化与仅记住变量值的 ByVal 相反。更改方法中的 ByVal 变量不会影响调用它的变量。
采纳答案by Kayaman
You can't. Everything in Java is passed by value, including object references. However you could create a "holder" object, and modify its value inside a method.
你不能。Java 中的一切都是按值传递的,包括对象引用。但是,您可以创建一个“持有者”对象,并在方法中修改其值。
public class Holder<T> {
T value;
public Holder(T value) {
this.value = value;
}
// getter/setter
}
public void method(Holder<Foo> foo) {
foo.setValue(something);
}
回答by nos
Java does not have an equivialent.
Java 没有等效项。
You either need to return the object from your method, and assign it back, e.g.
您要么需要从您的方法返回对象,并将其分配回来,例如
myInteger = doSomething(myInteger);
Or you need to make a wrapper object, these are often name a Holder.
If you have a variable named myInteger
that you want some method to change, you
pass it to that method as a member of the "Holder" class.
或者您需要制作一个包装对象,这些通常称为 Holder。如果您有一个命名的变量myInteger
想要更改某些方法,请将其作为“Holder”类的成员传递给该方法。
e.g. (This can naturally be made into a generic)
eg(这自然可以做成泛型)
class IntegerHolder {
public Integer myInteger;
}
IntegerHolder myHolder;
myHolder.myInteger = myInteger;
doSomething(myHolder);
//use the possibly altered myHolder.myInteger now.
Inside doSomething, you can now change myHolder.myInteger , and the method calling doSomething() can see that change, e.g.
在 doSomething 中,您现在可以更改 myHolder.myInteger ,调用 doSomething() 的方法可以看到该更改,例如
void doSomething(IntegerHolder holder)
{
holder.myInteger = holder.myInteger * 100;
}