2024-09-21 08:00:04

Java中的全局变量

如何在Java中定义全局变量?


当前回答

理解问题

我将全局变量限定为可以在代码中的任何地方访问和更改的变量,而无需关心静态/实例调用或从一个类传递任何引用到另一个类。

通常是A类

public class A {
    private int myVar;

    public A(int myVar) {
        this.myVar = myVar;
    }

    public int getMyVar() {
        return myVar;
    }

    public void setMyVar(int mewVar) {
        this.myVar = newVar;
    }
}

并且想在类B中访问和更新myvar,

public class B{

    private A a;

    public void passA(A a){
        this.a = a;
    }

    public void changeMyVar(int newVar){
        a.setMyvar(newVar);
    }
}

你需要引用类a的一个实例,并像这样更新类B的值:

int initialValue = 2;
int newValue = 3;
A a = new A(initialValue);
B b = new B();
b.passA(a);
b.changeMyVar(newValue);
assertEquals(a.getMyVar(),newValue); // true

解决方案

所以我的解决方案,(即使我不确定这是否是一个好的实践),是使用单例:


public class Globals {
    private static Globals globalsInstance = new Globals();

    public static Globals getInstance() {
        return globalsInstance;
    }

    private int myVar = 2;

    private Globals() {
    }

    public int getMyVar() {
        return myVar;
    }

    public void setMyVar(int myVar) {
        this.myVar = myVar;
    }
}

现在你可以在任何地方获得全局唯一实例:

Globals globals = Globals.getInstance();
// and read and write to myVar with the getter and setter like 
int myVar = globals.getMyVar();
global.setMyVar(3);

其他回答

如果需要更新全局属性,可以使用简单的getter/setter包装器类作为全局变量。下面是一个典型的例子。

public class GlobalHolder {

    private static final GlobalHolder INSTANCE = new GlobalHolder();

    private volatile int globalProperty;

    public static GlobalHolder getInstance() {
        return INSTANCE;
    }

    public int getGlobalProperty() {
        return globalProperty;
    }

    public void setGlobalProperty(int globalProperty) {
        this.globalProperty = globalProperty;
    }

    public static void main(String[] args) {
        GlobalHolder.getInstance().setGlobalProperty(10);
        System.out.println(GlobalHolder.getInstance().getGlobalProperty());
    }
}

正如你可能从答案中猜到的那样,Java中没有全局变量,你唯一能做的就是创建一个具有静态成员的类:

public class Global {
    public static int a;
}

你可以在Global中使用它。在其他地方。然而,如果你使用Java 1.5或更高版本,你可以使用导入静态魔法,使它看起来更像一个真正的全局变量:

import static test.Global.*;

public class UseGlobal {
    public void foo() {
        int i = a;
    }
}

瞧!

现在这还远远不是最佳实践,所以你可以在广告中看到:不要在家里这样做

public class GlobalClass {
     public static int x = 37;
     public static String s = "aaa";
}

这样你就可以用GlobalClass访问它们。x和GlobalClass.s

非常简单:

class UseOfGlobal
{
private static int a;
private static int b;
}

但是在方法块中尽可能地定义局部变量总是好的。

另一种方法是创建一个这样的界面:

public interface GlobalConstants
{
  String name = "Chilly Billy";
  String address = "10 Chicken head Lane";
}

任何需要使用它们的类只需要实现接口:

public class GlobalImpl implements GlobalConstants
{
  public GlobalImpl()
  {
     System.out.println(name);
  }
}