Java:< init>之间有什么区别?和< clinit>? [英] Java: What is the difference between <init> and <clinit>?

查看:89
本文介绍了Java:< init>之间有什么区别?和< clinit>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解以下文字......这是否意味着< clinit> 适用于空构造函数?为什么重要的是有两个不同的版本?

I am unable to understand the following text... Does it mean that <clinit> is for empty constructors? Why is important to have two different versions?

https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html


2.9. Special Methods

在Java虚拟机级别,每个构造函数(第2.12节)都显示为实例具有
特殊名称< init> 的初始化方法。该名称由编译器提供。因为
名称< init> 不是有效的标识符,所以它不能直接用于用Java编程语言编写的
程序。实例
初始化方法可以仅通过invokespecial指令在Java虚拟
机器内调用,并且它们可以在未初始化的类实例上仅调用
。实例初始化方法
接受构造函数的访问权限(第2.7.4节),从中获取

At the level of the Java virtual machine, every constructor (§2.12) appears as an instance initialization method that has the special name <init>. This name is supplied by a compiler. Because the name <init> is not a valid identifier, it cannot be used directly in a program written in the Java programming language. Instance initialization methods may be invoked only within the Java virtual machine by the invokespecial instruction, and they may be invoked only on uninitialized class instances. An instance initialization method takes on the access permissions (§2.7.4) of the constructor from which it was derived.

一个类或interface最多有一个类或接口初始化方法,并通过调用
方法进行初始化(第2.17.4节)。类或接口的初始化方法是静态
并且不带参数。它具有特殊名称< clinit> 。此名称是由编译器提供的
。由于名称< clinit> 不是有效的
标识符,因此不能直接在以
Java编程语言编写的程序中使用。类和接口初始化方法
由Java虚拟机隐式调用;它们永远不会直接从任何Java虚拟机inw2struction中调用
,但是
仅作为类初始化过程的一部分间接调用。

A class or interface has at most one class or interface initialization method and is initialized (§2.17.4) by invoking that method. The initialization method of a class or interface is static and takes no arguments. It has the special name <clinit>. This name is supplied by a compiler. Because the name <clinit> is not a valid identifier, it cannot be used directly in a program written in the Java programming language. Class and interface initialization methods are invoked implicitly by the Java virtual machine; they are never invoked directly from any Java virtual machine inw2struction, but are invoked only indirectly as part of the class initialization process.


推荐答案

< init> 是实例的(或其中一个)构造函数,并且非静态字段初始化。

<init> is the (or one of the) constructor(s) for the instance, and non-static field initialization.

< clinit> 是类的静态初始化块和静态字段初始化。

<clinit> are the static initialization blocks for the class, and static field initialization.

class X {

   static Log log = LogFactory.getLog(); // <clinit>

   private int x = 1;   // <init>

   X(){
      // <init>
   }

   static {
      // <clinit>
   }

}

这篇关于Java:&lt; init&gt;之间有什么区别?和&lt; clinit&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆