gpt4 book ai didi

java - 类 body 中的括号有什么作用?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:40:04 25 4
gpt4 key购买 nike

我有其他开发人员编写的此类:

public class ManifestFile implements Serializable {

private final static DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
private final static XPathFactory xPathFactory = XPathFactory.newInstance();
private final static DateFormat YYYYMMDD = new SimpleDateFormat("yyyyMMdd");
private final String uuid;
private final Set<File> attachments = new LinkedHashSet<File>();
private final transient ApplicationContext applicationContext = JavaService.INSTANCE.getApplicationContext();
private final transient File attachmentDirectory;
private final Date processAfter = new Date(System.currentTimeMillis() + 3 * 1000 * 60);

{
try {
documentBuilderFactory.setNamespaceAware(true);
final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new StreamSource(getClass().getResourceAsStream("/StrategicEmail5.xsd")));
documentBuilderFactory.setSchema(schema);
documentBuilderFactory.setValidating(true);
} catch (Throwable t) {
throw new RuntimeException(t);
}
}

我对这部分感到惊讶:

{
try {
documentBuilderFactory.setNamespaceAware(true);
final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new StreamSource(getClass().getResourceAsStream("/StrategicEmail5.xsd")));
documentBuilderFactory.setSchema(schema);
documentBuilderFactory.setValidating(true);
} catch (Throwable t) {
throw new RuntimeException(t);
}
}

有人可以解释一下这段代码是否有效以及在任何方法体之外使用 {} 的优势是什么?

最佳答案

这是一个实例初始化 block 。它作为类实例初始化的一部分被调用。

您还可以在这样的 block 前面加上“static”,以便在 初始化时调用一次。这称为静态初始化程序。

来自Java Language Specification :

8.6. Instance Initializers

An instance initializer declared in a class is executed when an instance of the class is created (§12.5, §15.9, §8.8.7.1)....

  • It is a compile-time error if an instance initializer cannot complete normally (§14.21).
  • It is a compile-time error if a return statement (§14.17) appears anywhere within an instance initializer.
  • Instance initializers are permitted to refer to the current object via the keyword this (§15.8.3), to use the keyword super (§15.11.2, §15.12), and to use any type variables in scope.
  • Use of instance variables whose declarations appear textually after the use is sometimes restricted, even though these instance variables are in scope. See §8.3.2.3 for the precise rules governing forward reference to instance variables.

Exception checking for an instance initializer is specified in §11.2.3.

关于java - 类 body 中的括号有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17147977/

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