How are enums internally represented in Java?

后端 未结 5 1656
南旧
南旧 2020-12-15 18:54

Java enums are classes. They are compiled as classes.

How will the following example be compiled? What is its \"class version\"? What is the exact class cod

5条回答
  •  北海茫月
    2020-12-15 19:08

    The output of javap -private for this is:

    public final class Ordinals extends java.lang.Enum {
      public static final Ordinals FIRST;
      public static final Ordinals SECOND;
      public static final Ordinals THIRD;
      private java.lang.String notation;
      private static final Ordinals[] $VALUES;
      public static Ordinals[] values();
      public static Ordinals valueOf(java.lang.String);
      private Ordinals(java.lang.String);
      public java.lang.String getNotation();
      static {};
    }
    

    As you see, the compiler added a few things.

    There is a synthetic Array $VALUES, which is going to be copied out whenever you call the values() method.

    The values() method itself is added to the class, to conform to the requirement of every enum that there should be a static values() method returning an array of all the enum constants. Why is it added by the compiler rather than inherited from Enum()? Because it is static.

    In the same manner, valueOf has been added. It is implemented by calling the static Enum.valueOf.

    One thing that you do not see in this listing is that the constructors have two additional, unseen parameters, which are passed when the enum constants are set up. They are the constant's name and its ordinal number. They are passed up to the super() constructor from Enum and used for the methods name() and ordinal() which are inherited from it.

提交回复
热议问题