Java 基础知识:没有名称或返回类型的静态函数

发布于 2024-10-31 22:28:22 字数 460 浏览 1 评论 0原文

public class Main {
    public static final Logger LOGGER = Logger.getLogger(Main.class.getName());

    static {
        try {
             LOGGER.addHandler(new FileHandler("errors.log",true));
        }
        catch(IOException ex) {
             LOGGER.log(Level.WARNING,ex.toString(),ex);
        }
    }
...

我想知道这个无名静态函数是做什么用的。

我从来没有在java中见过这样的东西(我目前正在学习)。

它是做什么用的?

通常什么时候使用?

程序中什么时候执行这个?

public class Main {
    public static final Logger LOGGER = Logger.getLogger(Main.class.getName());

    static {
        try {
             LOGGER.addHandler(new FileHandler("errors.log",true));
        }
        catch(IOException ex) {
             LOGGER.log(Level.WARNING,ex.toString(),ex);
        }
    }
...

I'm wondering what is this nameless static function about.

I never saw anything like this in java (which I'm currently learning).

What is it for ?

When is it typically used ?

When is this gonna be executed in the program ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

悲念泪 2024-11-07 22:28:22

这称为静态块,仅在初始化期间执行一次。另外,如果有多个静态初始化块,则运行时保证将按照它们在源代码中出现的顺序调用它们。

这是一个很好的解释,带有一些示例代码。
https://www.geeksforgeeks.org/g-fact-79/

That is called a static block and will only be executed once during initialization. Also, if there are more than one static initialization blocks, the run time guarantees that they will be called in the order they appear in the source code.

Here is a pretty good explanation with some example code a.
https://www.geeksforgeeks.org/g-fact-79/

韬韬不绝 2024-11-07 22:28:22

它在类加载时执行一次。在这种特定情况下,它为应用程序设置一个记录器。

It is executed once when the class is loaded. In this specific case it sets up a logger for the application.

情深已缘浅 2024-11-07 22:28:22

您只能在静态块中使用静态成员变量。并通知即使您多次调用构造函数静态块也只会在JVM上运行一次。

为什么我们需要静态块?因为我们无法在构造函数中初始化我们的static final成员变量,所以它没有任何意义。

因此,您可以使用构造函数初始化静态变量,因为它们是按实例创建的。并且您应该在静态块中初始化静态最终变量。非最终静态成员变量的初始化可以写在静态块内,也可以不写,这是一个选择。您可能希望在创建时在每个实例上初始化相同的值,然后在构造函数中分配静态变量以重置静态变量。如果你只想设置一次静态变量,那么即使它不是final成员变量,那么你也必须在static块内编写init语句。

这是一个简单的演示;

A - 具有静态初始化块的示例模型类

public class SampleModel {

    private int index;                          // Will be init within the constructor
    private static final int MAX_VALUE;         // Will be init within static block
    private static String messageOfTheDay;      // Will be init within static block

    // Argument Constructor
    public SampleModel(int index) { 
        this.index = index;
        System.out.println("Constructor called");
    }

    // static block, will be run only once!
    static {
        System.out.println("WARNING: Static Block called !");

        MAX_VALUE = 69;
        messageOfTheDay = "I'm here";
    }

    public String getMessageOfTheDay() {
        return messageOfTheDay;
    }

    public int getMaxValue() {
        return MAX_VALUE;
    }

    public int getIndex() {
        return index;
    }

}

B - 演示代码

public class StaticBlockDemo {

    public static void main(String[] args) {
        SampleModel obj1 = new SampleModel(1);
        SampleModel obj2 = new SampleModel(2);
        SampleModel obj3 = new SampleModel(3);

        System.out.println();
        System.out.println( "obj1 : index    : " + obj1.getIndex() );
        System.out.println( "obj1 : Max Value: " + obj1.getMaxValue() );
        System.out.println( "obj1 : Max MOTD : " + obj1.getMessageOfTheDay() + "\n");

        System.out.println( "obj2 : index    : " + obj2.getIndex() );
        System.out.println( "obj2 : Max Value: " + obj2.getMaxValue() );
        System.out.println( "obj2 : Max MOTD : " + obj2.getMessageOfTheDay() + "\n");

        System.out.println( "obj3 : index    : " + obj3.getIndex() );
        System.out.println( "obj3 : Max Value: " + obj3.getMaxValue() );
        System.out.println( "obj3 : Max MOTD : " + obj3.getMessageOfTheDay() + "\n");

    }

}

C - 输出

WARNING: Static Block called !
Constructor called
Constructor called
Constructor called

obj1 : index    : 1
obj1 : Max Value: 69
obj1 : Max MOTD : I'm here

obj2 : index    : 2
obj2 : Max Value: 69
obj2 : Max MOTD : I'm here

obj3 : index    : 3
obj3 : Max Value: 69
obj3 : Max MOTD : I'm here

通知在输出中,构造函数 被调用 3 次,但 静态块 仅被调用一次。

You can only work with static member variables with a static block. And notify that even you call the constructor multiple times, static block will run only once on JVM.

Why we need static block ? Because we cannot initialize our static final member variables within the constructor, it does not make any sense.

So, you can init your static variables with Constructor, because they are created per instance. And you should init your static final variables within a static block. Initialization of non-final static member variables are either can be written inside the static block or not, that's a choice. You may want to init the same value on each instance at creation, then you assign the static variable within the Constructor to reset the static variable. If you just want to set the static variable once, then even if it is not a final member variable, then you must write init statement inside the static block.

Here is a simple demo;

A - Sample Model Class With A Static Initialization Block

public class SampleModel {

    private int index;                          // Will be init within the constructor
    private static final int MAX_VALUE;         // Will be init within static block
    private static String messageOfTheDay;      // Will be init within static block

    // Argument Constructor
    public SampleModel(int index) { 
        this.index = index;
        System.out.println("Constructor called");
    }

    // static block, will be run only once!
    static {
        System.out.println("WARNING: Static Block called !");

        MAX_VALUE = 69;
        messageOfTheDay = "I'm here";
    }

    public String getMessageOfTheDay() {
        return messageOfTheDay;
    }

    public int getMaxValue() {
        return MAX_VALUE;
    }

    public int getIndex() {
        return index;
    }

}

B - Demo Code

public class StaticBlockDemo {

    public static void main(String[] args) {
        SampleModel obj1 = new SampleModel(1);
        SampleModel obj2 = new SampleModel(2);
        SampleModel obj3 = new SampleModel(3);

        System.out.println();
        System.out.println( "obj1 : index    : " + obj1.getIndex() );
        System.out.println( "obj1 : Max Value: " + obj1.getMaxValue() );
        System.out.println( "obj1 : Max MOTD : " + obj1.getMessageOfTheDay() + "\n");

        System.out.println( "obj2 : index    : " + obj2.getIndex() );
        System.out.println( "obj2 : Max Value: " + obj2.getMaxValue() );
        System.out.println( "obj2 : Max MOTD : " + obj2.getMessageOfTheDay() + "\n");

        System.out.println( "obj3 : index    : " + obj3.getIndex() );
        System.out.println( "obj3 : Max Value: " + obj3.getMaxValue() );
        System.out.println( "obj3 : Max MOTD : " + obj3.getMessageOfTheDay() + "\n");

    }

}

C - Output

WARNING: Static Block called !
Constructor called
Constructor called
Constructor called

obj1 : index    : 1
obj1 : Max Value: 69
obj1 : Max MOTD : I'm here

obj2 : index    : 2
obj2 : Max Value: 69
obj2 : Max MOTD : I'm here

obj3 : index    : 3
obj3 : Max Value: 69
obj3 : Max MOTD : I'm here

Notify that on the output, constructor is called 3 times however static block is only called once.

ι不睡觉的鱼゛ 2024-11-07 22:28:22

这是一个 静态初始化块,当类启动时运行一次已加载。它可用于初始化静态成员变量。

That's a Static Initialization Block which is run once when the class is loaded. It can be used to initialize static member variables.

那些过往 2024-11-07 22:28:22

这是一个 静态初始化程序,它将被执行在类初始化期间。正如您所看到的,它允许您在该阶段运行复杂的逻辑,包括异常处理。

It's a static initializer, which will be executed during class initialization. As you can see, it allows you to run complex logic during that stage, including exception handling.

睫毛上残留的泪 2024-11-07 22:28:22

它是一个初始化块,并在类加载时调用。

It a initialization block and called at the time of class loading.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文