简体   繁体   English

如何使方法在应用程序的生命周期中仅运行一次

[英]How to make a method run only once in the lifetime of application

I have a method that fills in a file with default values and I call that method in the constructor. 我有一个用默认值填充文件的方法,然后在构造函数中调用该方法。 I want that method to run only once ( I mean by only once so when the user press the play button /in eclipse/ then that method will not run in the second press. 我希望该方法仅运行一次(我的意思是仅运行一次,因此当用户按下播放按钮/ eclipse /时,该方法将不会在第二次按下时运行。

I have tried something like this but it doesn't work : 我已经尝试过类似的方法,但是不起作用:

private boolean defaultExecuted;
public synchronized void defaultStatsFile()
{
    if (defaultExecuted)
    {
        return;
    }
    else
    {
        fileReadNWrite.configWriter("panel1", "non-US incidents");
        fileReadNWrite.configWriter("panel2", "Hoaxes");
        fileReadNWrite.configWriter("panel3", "Under NUFORC investigation");
        fileReadNWrite.configWriter("panel4", "Likliest Shape");
        defaultExecuted = true;
    }

}

Is there a smarter way to fill in a file only once ? 有没有一种聪明的方法可以只填写一次文件?

Please if something is not clear comment and I will reply. 如果有不清楚的地方请发表评论,我会回复。 Any help is appreciated. 任何帮助表示赞赏。

Better you fill data in static block 更好地将数据填充到静态块中

like : including proper exception handling in Main class , this way no need to dependent on constructor to load default data in file. 例如:在Main类中包括适当的异常处理,这种方式无需依赖构造函数将默认数据加载到文件中。

static {
            fileReadNWrite.configWriter("panel1", "non-US incidents");
            fileReadNWrite.configWriter("panel2", "Hoaxes");
            fileReadNWrite.configWriter("panel3", "Under NUFORC investigation");
            fileReadNWrite.configWriter("panel4", "Likliest Shape");
            defaultExecuted = true;
}

因为所有代码都在类中,并且您可以有多个独立类加载器,所以您无法在Java中执行此操作,因此需要Java之外的一些资源。

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

相关问题 如何在Blackberry Java中只运行一次方法? - How to run a method only once in Blackberry Java? Java-使方法在初次启动时仅运行一次 - Java - make a method run only ONCE upon initial startup 有没有办法让一部分 paint() 方法在 Java 中只运行一次? - Is there a way to make a section of the paint() method only run once in Java? 调用的方法只能运行一次 - Invoked method only run once 如何在Android应用程序中仅运行一次线程? - How do I run a thread only once in an android application? TestNg:如何为 DataProvider 中的多个对象只运行一次方法 - TestNg : How to run a method only once for multiple objects in DataProvider 如何确保仅在给定特定参数的情况下才调用方法 - How to make sure that a method is called only once given specific parameters 创建一次只能运行的Java应用程序 - create a run-only-once java application 在paint()中仅运行一次方法(Java) - Run a method only once in paint () (Java) 如果一个带有 while-true 循环的方法只被调用一次,它会在线程的剩余生命周期内留在解释器中吗? - if a Method with a while-true loop gets invoked only once, it will stay in the interpreter for the remaining lifetime of it's thread?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM