Java Enum返回Int [英] Java Enum return Int

查看:175
本文介绍了Java Enum返回Int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法宣布一个枚举。我想要创建的是一个DownloadType的枚举,其中有3种下载类型(AUDIO,VIDEO,AUDIO_AND_VIDEO)。

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).

我已经实现了代码如下:

I have implemented the code as follows:

private enum DownloadType {
    AUDIO(0), VIDEO(1), AUDIO_AND_VIDEO(2);
    private final int value;

    private DownloadType(int value) {
        this.value = value;
    }
}

如果我这样使用它,这工作正常:

This works fine if I then use it like this:

DownloadType.AUDIO_AND_VIDEO.value;

但是,我想要它,所以我不必要求价值。我可能会误会,但是这是Java中的几个类工作的方式,例如Font,例如设置字体样式,您可以使用:

However, I would like it so that I don't have to ask for the 'value'. I may be mistaken, but this is the way several classes work in Java such as Font, for example to set a font style, you use:

Font.PLAIN

哪个返回一个int值,我们不使用: p>

Which returns an int value, we don't use:

Font.PLAIN.value


推荐答案

Font.PLAIN 不是一个枚举。它只是一个 int 。如果您需要从枚举中取值,则无法避免调用方法或使用 .value ,因为枚举实际上是其自己类型的对象,而不是原始图元

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.

如果您真的只需要一个 int 接受类型安全丢失,用户可能会将无效值传递给您的API,您可以将这些常量定义为 int 还:

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:

static class DownloadType {
    public static final int AUDIO = 0;
    public static final int VIDEO = 1;
    public static final int AUDIO_AND_VIDEO = 2;
}

顺便说一下, field实际上是多余的,因为还有一个 .ordinal()方法,所以你可以定义枚举作为:

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 }

,并使用

DownloadType.AUDIO_AND_VIDEO.ordinal()

这篇关于Java Enum返回Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆