final变量编译后的状态

直入正题,以下是一段测试程序:

public class Constants {

     private static final String A = "这是常量";
     private static String B = "这是静态变量";
     private static final String C = new String("这是String常量");
     private static final Teacher T = new Teacher("haha", 1L);

     private static final int i = 2;
     private static final Integer I = 2;

     public static void main(String[] args) {
           String c = "这是变量";
           System.out.println(A);
           System.out.println(B);
           System.out.println(C);
           System.out.println(c);
           System.out.println(T.toString());
           System.out.println(i);
           System.out.println(I);
     }
}

编译后的class,用jd-gui查看,如下:

public class Constants
{
  private static final String A = "这是常量";
  private static String B = "这是静态变量";
  private static final String C = new String("这是String常量");
  private static final Teacher T = new Teacher("haha", Long.valueOf(1L));
  private static final int i = 1;
  private static final Integer I = Integer.valueOf(2);

  public static void main(String[] args) {
    String c = "这是变量";
    System.out.println("这是常量");//直接是A的值
    System.out.println(B);
    System.out.println(C);
    System.out.println(c);
    System.out.println(T.toString());
    System.out.println(2);//直接是i的值
    System.out.println(I);
  }
}

由此可见,用final修饰的变量,如果是字符串,或者基本类型,在程序中引用,编译后就直接是变量的值,而不是变量,而引用类型,编译后仍是变量。

所以如果你的程序中用到了变量是final修饰的,并且变量是字符串或者是基本类型,那么在其他程序文件中用到了该变量,编译后就是值。如果在服务器上进行增量更新代码(只更新修改的文件的class),该变量值做了修改,也需要将用到该变量的文件进行编译后替换服务器上的class文件。否则,仍是用的原来的值。


你可能感兴趣的:(java)