前几天我在看一些代码时,我发现:
static {
...
}
我是c++出身,不知道为什么会有这个。这不是一个错误,因为代码编译良好。这个“静态”代码块是什么?
前几天我在看一些代码时,我发现:
static {
...
}
我是c++出身,不知道为什么会有这个。这不是一个错误,因为代码编译良好。这个“静态”代码块是什么?
当前回答
静态块可以用来表示程序也可以不使用主函数而运行。
//static block
//static block is used to initlize static data member of the clas at the time of clas loading
//static block is exeuted before the main
class B
{
static
{
System.out.println("Welcome to Java");
System.exit(0);
}
}
其他回答
它是一个静态初始化式。它在类加载时执行,是放置静态变量初始化的好地方。
从http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html
一个类可以有任意数量的静态初始化块,它们可以出现在类主体的任何地方。运行时系统保证静态初始化块按照它们在源代码中出现的顺序被调用。
如果您有一个带有静态查找映射的类,它可能是这样的
class MyClass {
static Map<Double, String> labels;
static {
labels = new HashMap<Double, String>();
labels.put(5.5, "five and a half");
labels.put(7.1, "seven point 1");
}
//...
}
它很有用,因为上面的静态字段不能使用labels = ....进行初始化它需要以某种方式调用put方法。
静态块用于初始化代码,并将在JVM加载类时执行。请参考下面给出详细解释的链接。 http://www.jusfortechies.com/java/core-java/static-blocks.php
是的,静态块用于初始化代码,它将在JVM开始执行时加载。
静态块在以前的Java版本中使用,但在最新版本中它不起作用。
静态块可以用来表示程序也可以不使用主函数而运行。
//static block
//static block is used to initlize static data member of the clas at the time of clas loading
//static block is exeuted before the main
class B
{
static
{
System.out.println("Welcome to Java");
System.exit(0);
}
}
它是一个代码块,当类装入器装入类时执行。它用于初始化类的静态成员。
也可以编写非静态初始化式,这看起来更奇怪:
public class Foo {
{
// This code will be executed before every constructor
// but after the call to super()
}
Foo() {
}
}