public class d {
public static void main(String[] args) throws IOException {
System.out.println(xxxx.test);
}
}class xxxx{
public final static String test="abc";
static{
System.out.println("111");
}
}为啥结果为:
abc
那个111怎么不打出来?????
public static void main(String[] args) throws IOException {
System.out.println(xxxx.test);
}
}class xxxx{
public final static String test="abc";
static{
System.out.println("111");
}
}为啥结果为:
abc
那个111怎么不打出来?????
不用load xxxx类
那public final static String test=new String("abc");
为什么有打呢?
并没有要求打印
如果你想打印的话可以用 Class class=new Class();
这样是把class类放入内存,故会打印
1种是编译期常量。比如 static final int,short,等基本类型及 String类型(直接赋值的)
另外一种是运行期常量 比如 static final long s=System.currentTimeMillis();
只有真正运行了才能确定下来对于编译期常量,编译的时候就替换掉的,如果引用到,不会直接引起了ide载入
对于执行期常量,必须等初始化的时候才确定,如果引用到的话,就会引起类的载入和初始化
你如果在: public static void main(String[] args) throws IOException {
System.out.println(xxxx.test);
中间加一句XXXX A = NEW XXXX();
比如这样:
public static void main(String[] args) throws IOException {
xxxx a = new xxxx();
System.out.println(xxxx.test);
那个111就运行出来了~
顺便补充点
这个问题涉及到类型(类或接口)主动使用和被动使用的问题
主动使用会导致类型初始化,而被动使用则不会
以下是6种类型主动使用的情况:创建类的新实例
调用类的静态方法
使用类或接口的静态字段,或对其赋值(final static 除外, 原因如redduke1202所说)
调用API中某些反射方法
初始化该类的子类
虚拟机启动时被表明为启动类的类(含有main方法的那个类)
xxxx(){
System.out.println(this.getClass().getClassLoader());
}
public final static String test="abc";
static{
System.out.println("111");
}
}public class tt extends ClassLoader{
public static void main(String[] args)throws Exception {
new xxxx();
tt t=new tt();
System.out.println(t.findLoadedClass("xxxx"));//为什么总是返回null???
}
}
public static void main(String[] args) throws IOException {
System.out.println(xxxx.test);
}
}class xxxx {
public final static String test;
static {
System.out.println("111");
test="abc";
}
}
或者
静态方法在内存中并未被程序的入口main方法调用
这一点和静态常量不同~~