static语句块的学习

引用eway 
一个类的运行,JVM做会以下几件事情 1、类装载 2、链接 3、初始化 4、实例化;而初始化阶段做的事情是初始化静态变量和执行静态方法等的工作。
Class.forName(args[0], true,off.getClass().getClassLoader()):JVM在load class之后就进行initial的工作。
Class.forName(args[0], false,off.getClass().getClassLoader()):JVM不需要在load class之后进行initial的工作。将initial的工作推迟到了newInstance的时候进行。
所以,static块的绝对不是什么“只是在类被第一次实体化的时候才会被仅仅调用一次”,而应该是在 类被初始化的时候,仅仅调用一次。

 

class StaticDemo{
	public static String info;
	private String other;
	
	static{
		info="静态语句块能操纵静态的对象";
		//other="无法操纵非static对象";
		System.out.println("==StaticDemo被加载到jvm==");
		System.out.println("info="+info);
	}
	public StaticDemo(){
		System.out.println("StaticDemo被实例化了");
	}
}

public class StaticTest {
	public static void main(String[] args){
		try{
			Class.forName("StaticDemo", true, StaticTest.class.getClassLoader());
		}catch(ClassNotFoundException e){
			e.printStackTrace();
		}		
	}
}
 

 运行结果:

 

==StaticDemo被加载到jvm==

info=静态语句块能操纵静态的对象

StaticDemo被实例化了

 

把参数true变成false,并实例化两个StaticDemo对象 。

class StaticDemo{
	public static String info;
	private String other;
	
	static{
		info="静态语句块能操纵静态的对象";
		//other="无法操纵非static对象";
		System.out.println("==StaticDemo被加载到jvm==");
		System.out.println("info="+info);
	}
	public StaticDemo(){
		System.out.println("StaticDemo被实例化了");
	}
}

public class StaticTest {
	public static void main(String[] args){
		try{
			Class.forName("StaticDemo", false, StaticTest.class.getClassLoader());
		}catch(ClassNotFoundException e){
			e.printStackTrace();
		}	
	        StaticDemo obj1=new StaticDemo();
		StaticDemo obj2=new StaticDemo();
	}
}
 

运行结果:

==StaticDemo被加载到jvm==

info=静态语句块能操纵静态的对象

StaticDemo被实例化了

StaticDemo被实例化了

 

 

 

 

你可能感兴趣的:(java,static块)