Java 类初始化顺序

package com.design.pattern.Singleton;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Singleton {

    private static String staticField = getStaticField();

    // 普通属性
    private String field = getField();

    {
        log.info("普通代码块初始化");
    }

    static {
        log.info("静态代码块初始化");
    }

    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }
    private Singleton (){
        log.info("构造函数初始化");
    }

    private static void show(){
        log.info("普通方法");
    }
    public static final Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public static String getStaticField() {
        String statiFiled = "Static Field Initial";
        log.info("静态属性初始化");
        return statiFiled;
    }

    public static String getField() {
        String filed = "Field Initial";
        log.info("普通属性初始化");
        return filed;
    }

    public static void main(String[] args) {
        Singleton.getInstance();
    }

}


输出结果

14:27:50.713 [main] INFO com.design.pattern.Singleton.Singleton - 静态属性初始化
14:27:50.723 [main] INFO com.design.pattern.Singleton.Singleton - 静态代码块初始化
14:27:50.723 [main] INFO com.design.pattern.Singleton.Singleton - 普通属性初始化
14:27:50.723 [main] INFO com.design.pattern.Singleton.Singleton - 普通代码块初始化
14:27:50.724 [main] INFO com.design.pattern.Singleton.Singleton - 构造函数初始化

你可能感兴趣的:(Java 类初始化顺序)