如何在Java中定义全局变量?
当前回答
创建一个独立的文件。java使用第一个解决方案,就可以了。你也可以在应用程序中这样做,例如,全局变量对你当前的应用程序是特殊的,等等:
在开头创建一个类,并在其中声明你的变量:
class Globals {
static int month_number;
static String month_name;
}
然后你可以访问这些变量——使用它们作为“全局变量”。Month_number ',等等——从你的应用程序的任何地方。
其他回答
在Java中没有全局变量
然而,我们所拥有的是一个静态关键字,这就是我们所需要的。 在Java中,类之外不存在任何东西。static关键字表示一个类变量,与实例变量相反,它只有一个副本,并且它超越了创建的该类的所有实例,这意味着它的值可以在任何时候在所有实例之间更改和访问。
如果您需要一个可以超出作用域访问的全局变量,那么这就是您需要的变量,但它的作用域只存在于类所在的位置,仅此而已。
创建一个独立的文件。java使用第一个解决方案,就可以了。你也可以在应用程序中这样做,例如,全局变量对你当前的应用程序是特殊的,等等:
在开头创建一个类,并在其中声明你的变量:
class Globals {
static int month_number;
static String month_name;
}
然后你可以访问这些变量——使用它们作为“全局变量”。Month_number ',等等——从你的应用程序的任何地方。
如果需要更新全局属性,可以使用简单的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());
}
}
public class GlobalClass {
public static int x = 37;
public static String s = "aaa";
}
这样你就可以用GlobalClass访问它们。x和GlobalClass.s
很多很好的答案,但我想给出这个例子,因为它被认为是一个类访问另一个类的变量的更合适的方式:使用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;
}
}
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap