什么时候执行类的静态块? [英] When is the static block of a class executed?

查看:144
本文介绍了什么时候执行类的静态块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个罐子,让我们称他们为a.jar和b.jar。

I have 2 jars, let's call them a.jar and b.jar.

b.jar取决于a.jar。

b.jar depends on a.jar.

在a.jar中,我定义了一个类,我们称之为StaticClass。在StaticClass中,我定义了一个静态块,调用名为init的方法:

In a.jar, I defined a class, let's call it StaticClass. In the StaticClass, I defined a static block, calling a method named "init" :

public class StaticClass {
  static {
    init();
  } 

  public void static init () {
    // do some initialization here
  }
}

在b.jar中,我有一个main,所以在main中,我希望调用init()方法,但实际上并没有。我怀疑是因为静态类没有被jvm加载,有人能告诉我

in b.jar, I have a main, so in the main, I expect that the init() method has been called, but actually not. I suspect that is because the StaticClass has not been loaded by the jvm, could anyone tell me


  1. 我的结论是否正确?

  2. 什么触发jvm加载类?

  3. 如何自动执行静态块?

谢谢

推荐答案

是的,你是对的。当JVM(类加载器 - 要特定)加载 StaticClass (这是第一次在代码中引用时出现)时,运行静态初始化块。

Yes, you are right. Static initialization blocks are run when the JVM (class loader - to be specific) loads StaticClass (which occurs the first time it is referenced in code).

您可以通过显式调用 StaticClass.init()来强制调用此方法,这比依赖JVM更可取。

You could force this method to be invoked by explicitly calling StaticClass.init() which is preferable to relying on the JVM.

您还可以尝试使用 Class.forName(String)来强制JVM加载类并调用其静态块。

You could also try using Class.forName(String) to force the JVM to load the class and invoke its static blocks.

这篇关于什么时候执行类的静态块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆