现在的位置: 首页 > 综合 > 正文

Be careful JVM

2014年12月13日 ⁄ 综合 ⁄ 共 1343字 ⁄ 字号 评论关闭

        Long time no to come here , for the company cut my Internet .

        Be careful the JVM compile the java file , especially, for the static final field . Here is an example .

 

B.java

package com.liangbinny.test;

public class B {
 public static final String T = "A+B";
}

 

A.java:

package com.liangbinny.test;

public class A {
 public static void main(String[] args) {
  System.out.println(B.T);
 }
}

 

After compiled A.java , and we can get A.class file ,,but if we decompile A.class , we will find that

 

// Decompiled by DJ v3.7.7.81 Copyright 2004 Atanas Neshkov  Date: 2013-5-14 20:56:25
// Home Page : http://members.fortunecity.com/neshkov/dj.html  - Check often for new version!
// Decompiler options: packimports(3)
// Source File Name:   A.java

package com.liangbinny.test;

import java.io.PrintStream;

public class A
{

    public A()
    {
    }

    public static void main(String args[])
    {
        System.out.println("A+B");
    }
}

 

 

Anything different with A.java ?

 

Yes , we never see   System.out.println(B.T); code , but we see System.out.println("A+B"); .

 

So , if a lib contain A.class and B.class ,  we change B.java , we not only need replace B.class file , we need replace A.class too.

We should be careful JVM compile the java code .

 

For more examples ,

 

How many String object create about this code ?

String s = "a"+"b+"c";

the answer is only one . as "abc"

 

For more examples ,

String a = "a";

String s = a +"b"+"c";

the answer is 4 ,  as "a", "b","c" , and "abc"

 

how about this ?

String a = "a";

String s = "b"+"c"+a;

the answer is 3, as "a","bc","abc"

 

That's all .

 

 

 

 

 

 

 

抱歉!评论已关闭.