欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

init vs clinit

程序员文章站 2022-03-05 15:39:18
...

what's clinit

上文提到clinit关键字,这个到底是什么意思?

摘自jdk 官方文档

2.9. Special Methods
At the level of the Java Virtual Machine, every constructor written in the Java programming language (JLS §8.8) 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 (§invokespecial), and they may be invoked only on uninitialized class instances. An instance initialization method takes on the access permissions (JLS §6.6) of the constructor from which it was derived.

在JVM层面,任何一个被JAVA编写显示地初始化类的方法有一个特定的名称叫"<init>"方法.这个名称由编译器提供,因为这个名称在JAVA语言里不是一个有效的标识符,所以它不能被java语言直接使用。<init>只能由JVM通过"invokespecial"指令调用.并且只能被未初始化的类实例调用.<init>方法要接受构造方法的访问权限。

A class or interface has at most one class or interface initialization method and is initialized (§5.5) by invoking that method. The initialization method of a class or interface has the special name <clinit>, takes no arguments, and is void (§4.3.3).

类或接口最多有一个"class or interface initialization method",该方法被调用时即初始化。这个方法有一个定的名字为"<clinit>",这个方法没有参数并且返回值为void

Other methods named <clinit> in a class file are of no consequence. They are not class or interface initialization methods. They cannot be invoked by any Java Virtual Machine instruction and are never invoked by the Java Virtual Machine itself.

这段很重要
在class 文件中的其他任何名字为<cliinit>的方法都无所谓。它们都不是"clss or interface initializtion method".它们不会被任何JVM指令调用。也不可能被JVM本身调用.

In a class file whose version number is 51.0 or above, the method must additionally have its ACC_STATIC flag (§4.6) set in order to be the class or interface initialization method.

在51或更高的版本,这个方法必须加ACC_STATIC 标记,以标识为<clinit>方法.

This requirement is new in Java SE 7. In a class file whose version number is 50.0 or below, a method named <clinit> that is void and takes no arguments is considered the class or interface initialization method regardless of the setting of its ACC_STATIC flag.

在 JDK1.7有一个新需求,在class文件中如果版本号是50或50以下,则要求<clinit>方法返回值为void,且无参数,但是否设置ACC_STATIC 标记已经无所谓了.

The name <clinit> 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 instruction, but are invoked only indirectly as part of the class initialization process.
<clinit>由编译器提供,所以在JAVA源文件里,它不是一个有效的标识符,它同样也不能直接被JAVA源文件编写。只能由JVM指令调用。

为什么叫clinit

class init ==>clinit

引用

https://*.com/questions/8517121/java-what-is-the-difference-between-init-and-clinit

asm 用户文档第59 页class init

asm4-guide.pdf P59

JDK1.6和1.7 50/51 版本对CLINIT方法限制验证

package com.sparrow.jdk.asm;

import java.io.FileOutputStream;

import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

public class Helloworld extends ClassLoader implements Opcodes {

    /**
     * public class Example {
     * <p>
     * static {
     * System.out.println("hello world");
     * }
     * public static void main (String[] args) {
     * System.out.println("Hello world!");
     * }
     *
     * @param args
     * @throws Exception
     */
    public static void main(final String args[]) throws Exception {


        //定义一个叫做Example的类
        ClassWriter cw = new ClassWriter(0);
        //50 即为JDK 1.6
        //通过个性版本号来验证是否需要ACC_STATIC FLAG
        cw.visit(V1_6, ACC_PUBLIC, "Example", null, "java/lang/Object", null);

        //生成默认的构造方法
        MethodVisitor initVisitor = cw.visitMethod(ACC_PUBLIC,
                "<init>",
                "()V",
                null,
                null);

        //生成构造方法的字节码指令
        initVisitor.visitVarInsn(ALOAD, 0);
        initVisitor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
        initVisitor.visitInsn(RETURN);
        initVisitor.visitMaxs(1, 1);
        initVisitor.visitEnd();

        //生成main方法
        initVisitor = cw.visitMethod(ACC_PUBLIC + ACC_STATIC,
                "main",
                "([Ljava/lang/String;)V",
                null,
                null);

        //生成main方法中的字节码指令
        initVisitor.visitFieldInsn(GETSTATIC,
                "java/lang/System",
                "out",
                "Ljava/io/PrintStream;");

        initVisitor.visitLdcInsn("Hello world!");
        initVisitor.visitMethodInsn(INVOKEVIRTUAL,
                "java/io/PrintStream",
                "println",
                "(Ljava/lang/String;)V", false);
        initVisitor.visitInsn(RETURN);
        initVisitor.visitMaxs(2, 2);
        //字节码生成完成
        initVisitor.visitEnd();

        MethodVisitor classInitVisitor = cw.visitMethod(ACC_PUBLIC, "<clinit>", "()V", null, null);
        classInitVisitor.visitCode();
        classInitVisitor.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
        classInitVisitor.visitLdcInsn("static hello world");
        classInitVisitor.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V",false);
        classInitVisitor.visitInsn(RETURN);
        classInitVisitor.visitMaxs(2, 0);
        classInitVisitor.visitEnd();

//        MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
//        mv.visitCode();
//        mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
//        mv.visitLdcInsn("static hello world");
//        mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V",false);
//        mv.visitInsn(RETURN);
//        mv.visitMaxs(2, 0);
//        mv.visitEnd();


        // 获取生成的class文件对应的二进制流
        byte[] code = cw.toByteArray();
        //将二进制流写到本地磁盘上
        FileOutputStream fos = new FileOutputStream("Example.class");
        fos.write(code);
        fos.close();

        //直接将二进制流加载到内存中
        Helloworld loader = new Helloworld();
        Class<?> exampleClass = loader.defineClass("Example", code, 0, code.length);

        //通过反射调用main方法
        exampleClass.getMethods()[0].invoke(null, new Object[]{null});
    }
}

静态内部类的单例模式

代码略

?

clinit只调用一次,同步锁验证