gpt4 book ai didi

java - 是否可以在静态 block 中创建对象?

转载 作者:行者123 更新时间:2023-11-30 08:54:00 24 4
gpt4 key购买 nike

我对静态 block 有点困惑。如果我们在这里谈论 system.out.println 方法 system 是一个类,out 是具有 printstream 引用 ID 的引用变量 在静态 block 中声明的类然后如何在静态 block 中创建任何对象,因为静态 block 总是在类加载时执行,而对象是在运行时创建的...我如何才能改变黑白加载时间和运行时间..

最佳答案

静态 block

静态 block 是一个静态初始化器(类初始化器)。您可以使用它来初始化类或在类加载期间执行一些逻辑。如果删除 static 修饰符,则代码块是一个实例初始化器

例如,使用静态初始化程序,您可以使用数据库数据初始化映射,以便稍后在对象实例化期间使用。

您可以阅读 this link这很好地解释了这一点。

我觉得这句话很有用:

Static blocks are also called Static initialization blocks. A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:

static {
// whatever code is needed for initialization goes here
}

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code. And dont forget, this code will be executed when JVM loads the class. JVM combines all these blocks into one single static block and then executes.

例如,这段代码:

public class StaticExample{
static {
System.out.println("This is first static block");
}

public StaticExample(){
System.out.println("This is constructor");
}

public static String staticString = "Static Variable";

static {
System.out.println("This is second static block and "
+ staticString);
}

public static void main(String[] args){
StaticExample statEx = new StaticExample();
StaticExample.staticMethod2();
}

static {
staticMethod();
System.out.println("This is third static block");
}

public static void staticMethod() {
System.out.println("This is static method");
}

public static void staticMethod2() {
System.out.println("This is static method2");
}
}

生成此输出:

This is first static block
This is second static block and Static Variable
This is static method
This is third static block
This is constructor
This is static method2

静态方法(替代静态 block )

您可以编写一个私有(private)静态方法来实现相同的目的,使用私有(private)静态方法的一个优点是,如果您需要重新初始化类变量,它们可以在以后重用。

例如:

class Whatever {
public static varType myVar = initializeClassVariable();

private static varType initializeClassVariable() {

// initialization code goes here
}
}

关于java - 是否可以在静态 block 中创建对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29579350/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com