Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于静态代码块执行时机的问题 #1245

Closed
Q-Bug4 opened this issue Jun 14, 2021 · 1 comment
Closed

关于静态代码块执行时机的问题 #1245

Q-Bug4 opened this issue Jun 14, 2021 · 1 comment
Labels
enhancement New feature or request or suggestion

Comments

@Q-Bug4
Copy link
Contributor

Q-Bug4 commented Jun 14, 2021

Java常见关键字总结中, 有如下说明:

🐛 修正(参见: issue #677) :静态代码块可能在第一次new的时候执行,但不一定只在第一次new的时候执行。比如通过 Class.forName("ClassDemo")创建 Class 对象的时候也会执行。

这句话有歧义, 我第一次看到的时候认为是static有可能会执行两次, 即"不一定只在第一次new的时候执行"我理解为"在new的时候执行static块后, 可能还会再执行一次static块".

当然通过代码验证以及查看issue后明白是指 "可以通过new或者Class.forName来执行static".
代码验证如下:

public void staticExecTimeTest(){
        try {
            Thread.sleep(2000);
            Class.forName("yourClassName");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

所以也是觉得消除歧义可能对于不熟悉的人更加友好.

@Snailclimb
Copy link
Owner

可以通过new或者Class.forName来执行static

已经修正~
image

@Snailclimb Snailclimb added the enhancement New feature or request or suggestion label Jun 14, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request or suggestion
Projects
None yet
Development

No branches or pull requests

2 participants