我在com.example包下写了一些文件,我想让它们可以共同编辑一个变量,达到这个变量对于每个文件都是同一个值,我具体怎么操作比较妥当?
定义一个常量类 , 里面的变量是 public static 修饰的就行
public class Constants {
public static String AUTHOR_NAME = "huazie";
}
设置公共字段就可以。在类的字段前面加上public修饰符就好了。注意要定义在方法外面。通常情况下还可以加上静态修饰符static,这样子对象和类名都可以引用这个变量。
那么此时源代码中的:
bundle = ResourceBundle.getBundle("messages", locale);
这一行应改为:
bundle = ResourceBundle.getBundle("com.messages", locale);
也就是说带上包名
要在多个文件中实现共享变量,可以使用以下方法之一:
// 在共享变量的Java类中
public class SharedVariable {
private static int sharedVariable;
public static int getSharedVariable() {
return sharedVariable;
}
public static void setSharedVariable(int value) {
sharedVariable = value;
}
}
// 在其他文件中使用共享变量
int value = SharedVariable.getSharedVariable();
SharedVariable.setSharedVariable(5);
// 在共享变量的Java类中
public class SharedVariable {
public static int sharedVariable;
}
// 在其他文件中使用共享变量
int value = SharedVariable.sharedVariable;
SharedVariable.sharedVariable = 5;
这些方法都可以实现在多个文件中共享变量的目的。选择哪种方法取决于你的具体需求和设计。