静态初始化块的使用

发布于 2024-08-19 18:13:40 字数 42 浏览 3 评论 0原文

我知道静态初始化块是如何工作的。
谁能告诉我它的一些典型用途。

I know how a static init block works.
Can anyone please tell me some typical uses of it.

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

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

发布评论

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

评论(7

死开点丶别碍眼 2024-08-26 18:13:40

当您想在一处初始化一个或多个静态变量时,

它很有用,因为您可以应用异常处理,而这是内联初始化所无法实现的。

例如:

public static ImageIcon defaultIcon = ImageIO.read(..);

可以用另一个应用程序来初始化

public static ImageIcon defaultIcon;
static {
   try {
       defaultIcon = ImageIO.read(..);
   } catch (IOException ex){
     System.out.println("No default icon available");
   }
}

复杂的初始化。例如,如果一项需要多行代码来初始化。假设您有一个配置:

public static Configuration configuration;
static {
     confuguration = new Configuration();
     configuration.setSomething(..);
     configuration.setSomethingElse(..);
     ...
}

第三种用途是初始化一些外部 API 基础设施。我当前项目中的一个例子:

static {
    org.apache.xml.security.Init.init();
}

但是,正如 Mykola Golubyev 指出的那样,静态初始化块会降低代码的可读性,因此请谨慎使用它们。静态方法更透明地完成同样的事情。

When you want to initialize one or more static variables in one place

It is useful, because you can apply exception handling, which is not possible with the in-line initialization.

For example:

public static ImageIcon defaultIcon = ImageIO.read(..);

can be initialized with

public static ImageIcon defaultIcon;
static {
   try {
       defaultIcon = ImageIO.read(..);
   } catch (IOException ex){
     System.out.println("No default icon available");
   }
}

Another application is complex initialization. For example, if an item requires more than one line of code to be initialized. Let's say you have a configuration:

public static Configuration configuration;
static {
     confuguration = new Configuration();
     configuration.setSomething(..);
     configuration.setSomethingElse(..);
     ...
}

A third usage is to initialize some external API infrastructure. One example from my current project:

static {
    org.apache.xml.security.Init.init();
}

But, as Mykola Golubyev noted, static initialization blocks make code less readable, so use them with caution. static methods do the same thing more transparently.

暮凉 2024-08-26 18:13:40

只是尽量避免使用静态初始化块。相反,您可以使用私有静态初始化函数,这将使您的代码更加干净。

我将参考@Bozho 的例子。

不要

public static Configuration configuration;
static {
     confuguration = new Configuration();
     configuration.setSomething(..);
     configuration.setSomethingElse(..);
     ...
}

使用代替

public static Configuration configuration = createConfiguration();

public static Configuration configuration = YourConfiguration.create();

Just try to avoid use of static initialization block. Instead you can use private static initialization functions which will make your code more clean.

I will refer to @Bozho for examples.

Do not do

public static Configuration configuration;
static {
     confuguration = new Configuration();
     configuration.setSomething(..);
     configuration.setSomethingElse(..);
     ...
}

Use instead

public static Configuration configuration = createConfiguration();

or

public static Configuration configuration = YourConfiguration.create();
秋千易 2024-08-26 18:13:40

它们通常与 JNI 代码结合使用,以确保加载所需的本机库:

class MyJniConnection {

    public static native void myJniCall();

    static {
        System.load("native.dll");
    }
}

They're often used in conjunction with JNI code to ensure that the required native library is loaded:

class MyJniConnection {

    public static native void myJniCall();

    static {
        System.load("native.dll");
    }
}
逆夏时光 2024-08-26 18:13:40
  • 初始化集合静态
    字段,如 Map、List、Set 等
  • 初始化基于 setter 的对象,该对象也是静态的
  • Initializing a collection static
    field, like Map, List, Set, etc
  • Initializing setter-based object which is also static
来世叙缘 2024-08-26 18:13:40

JDBC 驱动程序是一个流行的示例

为什么需要 Class.forName() 将驱动程序加载到内存中。答案很简单。根据 JDBC 规范的规定,所有 JDBC Driver 都有一个静态块,一旦加载 Driver 类,就会向 DriverManager 注册自己。像这样的事情:

static {
    try {
        java.sql.DriverManager.registerDriver(new Driver());
    } catch (SQLException E) {
        throw new RuntimeException("Can't register driver!");
    }
}

因此,当您编写时(例如,使用此处的 MySQL 驱动程序):

Class.forName("org.gjt.mm.mysql.Driver");

类加载器尝试加载并链接 org.gjt.mm.mysql.Driver 类,如果成功,则执行静态初始化块,并且 Driver 将自身注册到 DriverManager

JDBC Driver Is a Popular Example

Why do you need Class.forName() to load a driver into memory. The answer is simple. As stipulated in the JDBC specs, all JDBC Driver have a static block to register themselves with DriverManager as soon as the Driver class is loaded. Something like this:

static {
    try {
        java.sql.DriverManager.registerDriver(new Driver());
    } catch (SQLException E) {
        throw new RuntimeException("Can't register driver!");
    }
}

So, when you write (for example with the MySQL driver here):

Class.forName("org.gjt.mm.mysql.Driver");

The classloader attempts to load and link the org.gjt.mm.mysql.Driver class and, if successful, the static initialization block gets executed and the Driver registers itself with the DriverManager.

安穩 2024-08-26 18:13:40

它们可以用来创建 DSL,就像 JMock 所做的那样。例如,要设置将用户保存到数据库的期望:

Mockery context = new Mockery();
final Database database = context.mock(Database.class);    
...
context.checking(new Expectations() {{
    oneOf(database).save(user);
}});

// Rest of the test

They can be used to create a DSL, as JMock does. For instance, to set an expectation that a user will be saved to the database:

Mockery context = new Mockery();
final Database database = context.mock(Database.class);    
...
context.checking(new Expectations() {{
    oneOf(database).save(user);
}});

// Rest of the test
狼性发作 2024-08-26 18:13:40
  • static block :- 当我们想在类加载时执行代码时,我们可以将代码放在 static block 中...
  • init :- 当我们想在类的对象启动时执行代码时, 我们可以将代码放在 static block 中可以将代码放在 init 块中......
  • static block :- when we want to execute code at the time of loading of class then we can put the code in static block...
  • init :- when we want to execute code at the time of initiated of object of a class then we can put the code in init block....
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文