简体   繁体   English

如何从 static 方法访问全局非 static 变量

[英]How to access global non static variable from static method

I have main method in my java program, I want to store values in global variable because i want to access that values from different methods of the class, however I am not convinced to use static global variable, as the values in the variable keep on changing, so am afraid values which are declared as static may not change as it is defined on the class level, so I am looking for non static global variable.我在我的 java 程序中有主要方法,我想将值存储在全局变量中,因为我想从 class 的不同方法访问这些值,但是我不相信使用 ZA81259CEF8E959C6247DF1D456E5D2 变量中的值作为全局变量,改变,所以恐怕声明为 static 的值可能不会改变,因为它是在 class 级别上定义的,所以我正在寻找非 static 全局变量。 Can someone give an idea, how to achieve this.有人可以给出一个想法,如何实现这一目标。

I suggest you make a separate class with with variables you want to store, with proper getter and setter methods.我建议您使用要存储的变量以及适当的 getter 和 setter 方法制作一个单独的 class。 That way you keep the code more clean and maintainable and you follow the Separation of concerns principle, which tells us that every class should have it's own purpose.这样,您就可以使代码更加干净和可维护,并且遵循关注点分离原则,该原则告诉我们每个 class 都应该有自己的用途。

EG:例如:

 public class Person {
   private String name; // private = restricted access

   // Getter
   public String getName() {
   return name;
   }

  // Setter
  public void setName(String newName) {
  this.name = newName;
  }
}

 public class MyClass {
   public static void main(String[] args) {
     Person myObj = new Person();
     myObj.setName("John"); // Set the value of the name variable to "John"
     System.out.println(myObj.getName()); //Prints out name value
   }
 }

Since Java promotes the use of classes rather than global variables, I would highly recommend you to use a class for storing the data.由于 Java 提倡使用类而不是全局变量,我强烈建议您使用 class 来存储数据。 That way, you do not need to use static methods or static variables.这样,您就不需要使用 static 方法或 static 变量。

One example of this is shown below:一个例子如下所示:

import java.util.*;
public class Main{
    public static void main(String[] args) {
        int initialValue = 1;
        Holder holder = new Holder(initialValue);

        int currentValue = holder.getValue();
        System.out.println("Value after initial creation: " + currentValue);

        System.out.println("Set value to 10");
        holder.setValue(10);

        currentValue = holder.getValue();
        System.out.println("New value is " + currentValue);
    }
}

Holder class:支架 class:

public class Holder {
        private int val;
        public Holder(int value){
            setValue(value);
        }
        public void setValue(int value){
            this.val=value;
        }
        public int getValue(){
            return this.val;
        }
    }

To start a java class uses the "main" static method present in all normal java programs.要启动 java class 使用“主要” static 方法存在于所有正常的 Z93F725A47423FE1C886F 程序中。 HOWEVER, the "constructor" method (really just "constructor") is named after the "main class" name and is where you initialise variables whether you call a declared method in the class or retrieve a static variable from the starter method "main".但是,“构造函数”方法(实际上只是“构造函数”)以“主类”名称命名,无论您调用 class 中的声明方法还是从启动方法“main”检索 static 变量,都可以在其中初始化变量.

The main method does not require any passer method to obtain a static variable from it to either set a global static variable in the class because it is only 1 step in hierarchy "scope" in the class (this is why some frameworks pass variables to global without typing of the method but rather instead using "void" on the method declaration) BUT you cannot put a non static method call in a static section of code such as the main method. The main method does not require any passer method to obtain a static variable from it to either set a global static variable in the class because it is only 1 step in hierarchy "scope" in the class (this is why some frameworks pass variables to global无需键入方法,而是在方法声明中使用“void”)但是您不能在代码的 static 部分(例如 main 方法)中放置非 static 方法调用。

The way you remove static context from a variable is to make another variable with the same name in a non static context and cast the static variable to the non static instance. The way you remove static context from a variable is to make another variable with the same name in a non static context and cast the static variable to the non static instance.

eg for a global String primitive type variable from main method at construction time globally declare例如,在构造时全局声明来自 main 方法的全局 String 原始类型变量

static String uselessRef1 = ""; //  declared globally initialised

// following is declared inside the static method main
uselessRef1 = args[1]; // static argument 1 from the main method args[] array

// following is declared in global scope code or in the constructor code
    String uselessRef1b = (String)uselessRef1; // (String) cast removes the static context of the String type and copies to non static version of the type

While committed inline in the global declarations not in the constructor they are deemed to be loaded in the class constructor in sequence.虽然在全局声明中内联提交而不在构造函数中,但它们被视为按顺序加载到 class 构造函数中。

NB: You can put or make a static method in a non-static class but not the make a non static method in a static class. NB: You can put or make a static method in a non-static class but not the make a non static method in a static class.

import.javax.swing.*;
public class ExampleStaticRemoval{
static String uselessRef1 = ""; //  declared globally initialised
String uselessRef1b = ""; 
ExampleStaticRemoval(){

// following is declared in global scope code or in the constructor code
    uselessRef1b = (String)uselessRef1; // (String) cast removes the static context of the String type and copies to non static version of the type 
    printOut();

}// end constructor



    // program start method
    public static void Main(String[] args){
    new ExampleStaticRemoval();
        // static global class variable uselessRef1 is assigned the local method value
    // MUST BE OUTSIDE AT TOP TO BE GLOBAL
        uselessRef1 = args[0] +"  "+args[1]; // join static arguments 0 and 1 from the main method args[] array

}// end main



    public void printOut(){
    JOptionPane.showConfirmDialog(null,uselessRef1b, uselessRef1b, 0);
}//end method


} // end class

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM