2024-09-21 08:00:04

Java中的全局变量

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


要定义全局变量,可以使用静态关键字

public class Example {
    public static int a;
    public static int b;
}

现在你可以在任何地方访问a和b 通过调用

Example.a;

Example.b;

一般来说,全局变量(我假设您正在与C进行比较,Cpp)定义为公共静态final

like

class GlobalConstant{
    public static final String CODE  = "cd";
}

enum在这样的场景中也很有用:

例如Calendar.JANUARY)


你不。这是故意的。即使你能做,你也不应该做。

也就是说,您可以在一个名为Globals的类中创建一组公共静态成员。

public class Globals {
   public static int globalInt = 0;
   ///
}

但你真的不应该:)。认真. .不要这样做。


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

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


public class GlobalImpl {   

 public static int global = 5;

}

你可以在任何地方打电话:

GlobalImpl.global // 5

在Java中没有真正的全局变量。每个静态变量都必须属于某个类(如System.out),但是当你决定它将属于哪个类时,你可以从同一个类加载器加载的任何地方引用它。

注意,在更新时应始终保护静态变量以避免竞态条件。


你最好使用依赖注入:

public class Globals {
    public int a;
    public int b;
}

public class UsesGlobals {
    private final Globals globals;
    public UsesGlobals(Globals globals) {
        this.globals = globals;
    }
}

正如你可能从答案中猜到的那样,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;
    }
}

瞧!

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


在Java中没有全局变量,但是有带有公共字段的全局类。您可以使用java 5的静态导入特性使其看起来几乎像全局变量。


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

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

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

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

实际上,在java OO程序中没有“GLOBAL”的概念

尽管如此,你的问题背后还是有一定道理的,因为在某些情况下,你想在程序的任何部分运行一个方法。 例如——random()方法在Phrase-O-Matic应用程序;它是一个方法应该可以从程序的任何地方调用。

为了满足上面提到的"我们需要类全局变量和方法"

将一个变量声明为全局变量。

 1.Mark the variable as public static final While declaring.

将一个方法声明为全局方法。

 1. Mark the method as public static While declaring.

因为我将全局变量和方法声明为静态的,你可以在任何地方调用它们,只需借助下面的代码

ClassName。X

注意:根据需求,X可以是方法名或变量名,ClassName是你声明它们的类名。


除了常量,没有什么是全局的。

public class MyMainClass {
    public final static boolean DEBUGMODE=true;
}

把它放在你的主类中。在其他。java文件中,通过以下方式使用它:

if(MyMainClass.DEBUGMODE) System.out.println("Some debugging info");

确保当你把你的代码从剪辑室移出并发布时,你删除或注释掉了这个功能。

如果你有一个常用的方法,比如随机发生器,我建议你创建一个“工具箱”包!所有编码员都应该有一个,然后当你想在.java中使用它时,只需导入它!


要定义全局变量,可以使用静态关键字

public final class Tools {
  public static int a;
  public static int b;
}

现在您可以通过调用从任何地方访问a和b

Tools.a;
Tools.b;

你说得对……特别是在J2ME中… 可以通过将NullPointerException放入MidLet构造函数中来避免 (程序初始化)这行代码:

new Tools();

这确保了Tools将在任何指令之前分配 它使用了它。

就是这样!


很多很好的答案,但我想给出这个例子,因为它被认为是一个类访问另一个类的变量的更合适的方式:使用getter和setter。

The reason why you use getters and setters this way instead of just making the variable public is as follows. Lets say your var is going to be a global parameter that you NEVER want someone to change during the execution of your program (in the case when you are developing code with a team), something like maybe the URL for a website. In theory this could change and may be used many times in your program, so you want to use a global var to be able to update it all at once. But you do not want someone else to go in and change this var (possibly without realizing how important it is). In that case you simply do not include a setter method, and only include the getter method.

public class Global{
    private static int var = 5;

    public static int getVar(){
        return Global.var;
    }

    //If you do not want to change the var ever then do not include this
    public static void setVar(int var){
        Global.var = var;
    }
}

// Get the access of global while retaining priveleges.
// You can access variables in one class from another, with provisions.
// The primitive must be protected or no modifier (seen in example).

// the first class
public class farm{

  int eggs; // an integer to be set by constructor
  fox afox; // declaration of a fox object

  // the constructor inits
  farm(){
    eggs = 4;
    afox = new fox(); // an instance of a fox object

    // show count of eggs before the fox arrives
    System.out.println("Count of eggs before: " + eggs);

    // call class fox, afox method, pass myFarm as a reference
    afox.stealEgg(this);

    // show the farm class, myFarm, primitive value
    System.out.println("Count of eggs after : " + eggs);

  } // end constructor

  public static void main(String[] args){

    // instance of a farm class object
    farm myFarm = new farm();

  }; // end main

} // end class

// the second class
public class fox{

  // theFarm is the myFarm object instance
  // any public, protected, or "no modifier" variable is accessible
  void stealEgg(farm theFarm){ --theFarm.eggs; }

} // end class

在Java中没有全局变量

然而,我们所拥有的是一个静态关键字,这就是我们所需要的。 在Java中,类之外不存在任何东西。static关键字表示一个类变量,与实例变量相反,它只有一个副本,并且它超越了创建的该类的所有实例,这意味着它的值可以在任何时候在所有实例之间更改和访问。

如果您需要一个可以超出作用域访问的全局变量,那么这就是您需要的变量,但它的作用域只存在于类所在的位置,仅此而已。


一般来说,Java没有任何全局变量。除局部变量外,所有变量都属于程序中定义的任何类的作用域。 我们可以用静态变量来表示全局变量的作用域。


创建一个独立的文件。java使用第一个解决方案,就可以了。你也可以在应用程序中这样做,例如,全局变量对你当前的应用程序是特殊的,等等:

在开头创建一个类,并在其中声明你的变量:

class Globals {
  static int month_number;
  static String month_name;
}

然后你可以访问这些变量——使用它们作为“全局变量”。Month_number ',等等——从你的应用程序的任何地方。


从概念上讲,全局变量又称实例变量,是类级变量,即类级变量。,它们定义在类内部,但在方法之外。为了使它们完全可用,并直接使用它们,提供静态关键字。 因此,如果我正在编写一个简单的算术运算程序,它需要一个数字对,然后两个实例变量定义如下:

public class Add {
    static int a;
    static int b; 
    static int c;

    public static void main(String arg[]) {
        c=sum();
        System.out.println("Sum is: "+c); 
    }

    static int sum() {
       a=20;
       b=30;
       return a+b;   
    }
}

Output: Sum is: 50

此外,在实例变量之前使用static关键字使我们不必反复为相同的变量指定数据类型。直接写出变量即可。


如果没有静电,这也是可能的:

class Main {
  String globalVar = "Global Value";

  class Class1 {
    Class1() {
      System.out.println("Class1: "+globalVar);
      globalVar += " - changed";
  } }
  class Class2 {
    Class2() {
      System.out.println("Class2: "+globalVar);
  } }

  public static void main(String[] args) {  
    Main m = new Main();
    m.mainCode();
  }
  void mainCode() {
    Class1 o1 = new Class1();
    Class2 o2 = new Class2();
  }
}

/*
Output:
Class1: Global Value
Class2: Global Value - changed
*/

如果需要更新全局属性,可以使用简单的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的行业标准。它不是行业标准,因为它允许多个类异步操作数据,如果您正在运行一个多线程应用程序,从线程安全的角度来看,这将变得更加复杂和危险。使用全局变量无效还有其他各种原因,但如果您想避免这种情况,我建议您采用面向方面编程。

面向方面编程解决了这个问题,它让父类通过所谓的“建议”来负责作用域,它在代码中添加了额外的行为,而不需要实际修改它。它为横切关注点或全局变量的使用提供解决方案。

Spring是一个利用AOP的Java框架,虽然它传统上用于web应用程序,但核心应用程序可以在整个Java框架(包括8.0)中普遍使用。这可能是你想要进一步探索的方向。


理解问题

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

通常是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);

非常简单:

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

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


为了允许对另一个类的静态成员进行非限定访问,你也可以执行静态导入:

import static my.package.GlobalConstants;

现在,不是打印(GlobalConstants.MY_PASSWORD); 你可以直接使用常量:print(MY_PASSWORD)

“import”后面的“static”修饰符是什么意思?决定。

考虑Evan Lévesque关于承载常量的接口的回答。