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

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

问题描述

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

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

<块引用>

<代码>2.9.特殊方法

在 Java 虚拟机级别,每个构造函数(第 2.12 节)都作为实例初始化方法出现,具有特殊名称 <init>.此名称由编译器提供.因为name <init> 不是一个有效的标识符,它不能直接用于用 Java 编程语言编写的程序.实例初始化方法只能在 Java 虚拟中调用机器由 invokespecial 指令,它们只能被调用在未初始化的类实例上.实例初始化方法获取构造函数的访问权限(第 2.7.4 节)它是派生出来的.

一个类或接口最多有一个类或接口初始化方法,并通过调用它来初始化(第 2.17.4 节)方法.类或接口的初始化方法是静态的并且不接受任何论点.它具有特殊名称 <clinit>.这个名字是由编译器提供.因为名称 <clinit> 不是有效的标识符,它不能直接在编写的程序中使用Java 编程语言.类和接口初始化方法由 Java 虚拟机隐式调用;他们从来不是直接从任何 Java 虚拟机 inw2struction 调用,但仅作为类初始化过程的一部分间接调用.

解决方案

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

<clinit> 是类的静态初始化块,以及静态字段初始化.

class X {静态日志 log = LogFactory.getLog();//<clinit>私人 int x = 1;//<初始化>X(){//<初始化>}静止的 {//<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

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.

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> is the (or one of the) constructor(s) for the instance, and non-static field initialization.

<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天全站免登陆