[英]Permanent change of a variable in static method
Let's say I have a public class with static methods, one of them for example: 假设我有一个带静态方法的公共类,其中一个例如:
public static void test(boolean b){
b = !b;
}
Let's say this class name is Test. 假设这个类名是Test。 From another class, where I have a variable boolean a = false, I call
从另一个类,我有一个变量boolean a = false,我调用
Test.test(a);
How can I make it change a permanently, and not just change it in that static methods scope? 如何使其永久更改,而不仅仅是在静态方法范围内进行更改?
The only way to make the change permanent is to let the method have a return value and assign it to the variable : 使更改永久化的唯一方法是让方法具有返回值并将其分配给变量:
public static boolean test(boolean b){
return !b;
}
a = Test.test(a);
Use a static field: 使用静态字段:
public static boolean flag;
public static void test(boolean b){
flag = !b;
}
Then: 然后:
boolean a = true;
Test.test(a);
System.out.println( Test.flag); // false
in your Test
class you can define the boolean variable as static 在
Test
类中,您可以将boolean变量定义为static
public static boolean a;
and outside the class change or access it using Test.a=false;
在课外改变或使用
Test.a=false;
访问它Test.a=false;
or a=Test.a
或
a=Test.a
and if you need to use methods you can hide the static method with inheritance: 如果需要使用方法,可以使用继承隐藏静态方法:
public class HideStatic {
public static void main(String...args){
BaseA base = new ChildB();
base.someMethod();
}
}
class BaseA {
public static void someMethod(){
System.out.println("Parent method");
}
}
class ChildB extends BaseA{
public void someMethod(){
System.out.println("Child method");
}
}
You can pass an instance to method and use setters to change more variables at once. 您可以将实例传递给方法并使用setter一次更改更多变量。
public static void updateData(MyClass instance) {
instance.setX(1);
instance.setY(2);
}
I think you are asking for call by reference . 我想你是要求参考电话 。 You can get this in Java by using arrays:
您可以使用数组在Java中获取它:
public static void test(boolean[] b){
b[0] = !b[0];
}
boolean[] param = new boolean[] {a};
test(param);
a=param[0];
//a changed
This works, but it is ugly. 这有效,但很难看。 If you need to return more than one value, have a look at the Pair or Tuple structures.
如果需要返回多个值,请查看Pair或Tuple结构。
Sounds to me like you are looking for a Mutable Boolean
, the simplest of which is an AtomicBoolean . 听起来像你正在寻找一个Mutable
Boolean
,其中最简单的是AtomicBoolean 。
private void changeIt(AtomicBoolean b) {
b.set(!b.get());
}
public void test() {
AtomicBoolean b = new AtomicBoolean(false);
changeIt(b);
System.out.println(b);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.