Java中static修饰一段代码,实现加载时运行的用法

    技术2022-05-20  26

    package com.min.test; class AA{ // 加载时运行,与instance无关 static{ System.out.println("static block "); } AA() { System.out.println("AA()"); } } public class JavaTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { Class.forName("com.min.test.AA"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } // AA a = new AA(); } }

    输出结果:

    static block

     

    加上AA a = new AA();后,输出:

    static block AA()

     


    最新回复(0)