在 Java 中设置标志
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3608737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set the Flag in Java
提问by David Brown
How can set the flag to set the condition of displaying a message only once when the application gets loaded in Java Language.
当应用程序以 Java 语言加载时,如何设置标志以设置仅显示一次消息的条件。
Thanks, david
谢谢,大卫
采纳答案by Andreas Dolk
You could use a global flag store, based on enum
because we want Singleton behaviour. It could look like this:
您可以使用全局标志存储,enum
因为我们想要单例行为。它可能看起来像这样:
public enum Flag {
APPLICATION_LOADED(false), NEED_SAVING(true), CAN_EXIT(false) /*, ... */;
private boolean state;
private Flag(boolean initialState) {
this.state = initialState;
}
public boolean getState() {return state;}
public void setState(boolean state) {this.state = state;}
}
and use it like this
并像这样使用它
private void startApplication() {
// perform startup sequence
APPLICATION_LOADED.setState(true);
}
and later
然后
private void showMessage(Flag flag) {
if (flag.getState() == false) {
// perform displaying
}
}
回答by Marc-Christian Schulze
Just put your displaying code directly into the main method. So it executes only onces when the application is run.
只需将您的显示代码直接放入 main 方法中。所以它在应用程序运行时只执行一次。
回答by BalusC
Just have a boolean
field which you set true
or false
accordingly.
只需有一个boolean
您设置true
或false
相应的字段。
private boolean messageWasAlreadyDisplayed;
You can test it in an if
statement and handle accordingly.
您可以在if
语句中对其进行测试并进行相应处理。
if (!messageWasAlreadyDisplayed) {
displayMessage();
messageWasAlreadyDisplayed = true;
}
See also:
也可以看看:
回答by fish
I assume this would mean only once between runs? So only on the first time it's run. This you can do by storing the flag to a file. A good starting point would be to use java.util.Properties
which you can use for storing key-value pairs.
我认为这意味着两次运行之间只有一次?所以只在第一次运行时。这可以通过将标志存储到文件来完成。一个好的起点是使用java.util.Properties
它来存储键值对。
Something like this:
像这样的东西:
Properties properties = ... ; //initialize with the file
String key = "msgAlreadyDisplayed";
if (properties.getProperty(key) == null) {
//display the message
properties.getProperty(key, "true");
properties.save(....); //save to the file
}