Java Enum return Int

前端 未结 8 2032
小鲜肉
小鲜肉 2020-12-13 03:31

I\'m having trouble declaring an enum. What I\'m trying to create is an enum for a \'DownloadType\', where there are 3 download types (AUDIO, VIDEO, AUDIO_AND_VIDEO).

<
8条回答
  •  旧时难觅i
    2020-12-13 04:05

    Font.PLAIN is not an enum. It is just an int. If you need to take the value out of an enum, you can't avoid calling a method or using a .value, because enums are actually objects of its own type, not primitives.

    If you truly only need an int, and you are already to accept that type-safety is lost the user may pass invalid values to your API, you may define those constants as int also:

    public final class DownloadType {
        public static final int AUDIO = 0;
        public static final int VIDEO = 1;
        public static final int AUDIO_AND_VIDEO = 2;
    
        // If you have only static members and want to simulate a static
        // class in Java, then you can make the constructor private.
        private DownloadType() {}
    }
    

    By the way, the value field is actually redundant because there is also an .ordinal() method, so you could define the enum as:

    enum DownloadType { AUDIO, VIDEO, AUDIO_AND_VIDEO }
    

    and get the "value" using

    DownloadType.AUDIO_AND_VIDEO.ordinal()
    

    Edit: Corrected the code.. static class is not allowed in Java. See this SO answer with explanation and details on how to define static classes in Java.

提交回复
热议问题