Static {}在Java语法中的含义是什么? [英] What does Static {} mean in the Java Syntax?
本文介绍了Static {}在Java语法中的含义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到了这个Java代码:
I came across this Java code:
static {
String aux = "value";
try {
// some code here
} catch (Exception e) { }
String UUID_prefix = aux + ":";
}
我是Java的新手,请解释这里发生的事情。
I am new to Java, please explain what is happening here.
推荐答案
这是一个静态初始化块。可以把它想象成构造函数的静态版本。在实例化类时运行构造函数;静态初始化块在类加载时运行。
This is a static initialization block. Think of it like a static version of the constructor. Constructors are run when the class is instantiated; static initialization blocks get run when the class gets loaded.
您可以将它们用于这样的事情(显然是伪造的代码):
You can use them for something like this (obviously fabricated code):
private static int myInt;
static {
MyResource myResource = new MyResource();
myInt = myResource.getIntegerValue();
myResource.close();
}
请参阅有关初始化字段的Oracle教程。
这篇关于Static {}在Java语法中的含义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文