Java 如何创建带有条件的全局变量
我想创建一个全局变量,但我希望它是基于机器操作系统的两个值之一。我想我可以通过编写以下代码来做到这一点:Java 如何创建带有条件的全局变量,java,global-variables,Java,Global Variables,我想创建一个全局变量,但我希望它是基于机器操作系统的两个值之一。我想我可以通过编写以下代码来做到这一点: import java.lang.*; import java.util.Properties; public class constants { public static String driverFile = null; public static String storageDirectory = null; if (System.getProper
import java.lang.*;
import java.util.Properties;
public class constants {
public static String driverFile = null;
public static String storageDirectory = null;
if (System.getProperty("os.name").startsWith("Windows")){
storageDirectory = "C:\\Scripts\\Price_Tracker";
driverFile = "geckodriver-v0.27.0-win64.exe";
}else{//is linux
storageDirectory = "/Price_Tracker";
driverFile = "geckodriver-v0.27.0-linux64";
}// end if(System.getProperty("os.name").startsWith("Windows")
}//end public class constants
但我在说“”时出错了,我想做的是可能的吗
不能只使用随机浮动if语句。它需要在方法或初始化程序块中。查看静态初始化块。谢谢!我感谢你的帮助,我认为if语句只需要用一种方法,就像Michael所说的那样。谢谢它实际上被称为静态初始值设定项。当类加载到JVM中时,静态初始值设定项运行一次。静态初始值设定项是包装在静态{…}块中的所有代码。
public class constants {
public static String driverFile = null;
public static String storageDirectory = null;
static {
if (System.getProperty("os.name").startsWith("Windows")){
storageDirectory = "C:\\Scripts\\Price_Tracker";
driverFile = "geckodriver-v0.27.0-win64.exe";
}else{//is linux
storageDirectory = "/Price_Tracker";
driverFile = "geckodriver-v0.27.0-linux64";
}// end if(System.getProperty("os.name").startsWith("Windows")
}
}//end public class constants