为什么<filename> $ 1.class生成?</filename>

时间:2015-04-10 10:48:46

标签: java class enums switch-statement

enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}  

class Enum1 {  

  public static void main(String args[]) {  

    Day day=Day.MONDAY;  

    switch(day) {  
      case SUNDAY:   
        System.out.println("sunday");  
        break;  
      case MONDAY:   
        System.out.println("monday");  
        break;  
      default:  
        System.out.println("other day");
    }
  }
}

编译此代码时,我看到Enum1.classDay.classEnum1$1.class。当我注释掉switchcase部分时,只生成Enum1.classDay.class

switchcase中的内容是生成额外Enum1$1.class文件的原因?

1 个答案:

答案 0 :(得分:2)

对包javap中的类使用de.lhorn

<强> Day.class

public final class de.lhorn.so.Day extends java.lang.Enum<de.lhorn.so.Day> {
  public static final de.lhorn.so.Day SUNDAY;
  public static final de.lhorn.so.Day MONDAY;
  public static final de.lhorn.so.Day TUESDAY;
  public static final de.lhorn.so.Day WEDNESDAY;
  public static final de.lhorn.so.Day THURSDAY;
  public static final de.lhorn.so.Day FRIDAY;
  public static final de.lhorn.so.Day SATURDAY;
  public static de.lhorn.so.Day[] values();
  public static de.lhorn.so.Day valueOf(java.lang.String);
  static {};
}

<强> Enum1.class

public class de.lhorn.so.Enum1 {
  public de.lhorn.so.Enum1();
  public static void main(java.lang.String[]);
}

<强> Enum$1.class

class de.lhorn.so.Enum1$1 {
  static final int[] $SwitchMap$de$lhorn$so$Day;
  static {};
}

因此switch会导致javac生成额外的static final int[] $SwitchMap$de$lhorn$so$Day;