简体   繁体   English

Java-使方法在初次启动时仅运行一次

[英]Java - make a method run only ONCE upon initial startup

I'm working on a program that will include a method startup() for user configuration purposes. 我正在开发一个程序,其中包括用于用户配置目的的startup()方法。 I only want this method to run once, upon initial startup of the program. 我只希望该方法在程序初次启动时运行一次。 how would I go about doing this? 我将如何去做呢?

You can use static initializer block. 您可以使用静态初始化程序块。

public class MyClass {
static {
 // code to be executed once on startup
 }
}

Such static initializer blocks are executed when the class is loaded, even before constructor or main method is called. 此类静态初始化程序块在加载类时执行,甚至在调用constructormain方法之前也是如此。

You can have any number of these blocks and they will be executed in the order they appear in the code. 您可以有任意数量的这些块,它们将按照它们在代码中出现的顺序执行。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM