Java 枚举覆盖 toString()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7758313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:18:03  来源:igfitidea点击:

Java enum overriding toString()

javajpaenumstostring

提问by Patrick Grimard

I've never really made use of Java enum classes before for constant values, I've typically used the "public final" approach in the past. I've started using an enum now and I'm overriding the toString() method to return a different value than the enum name.

我以前从未真正将 Java 枚举类用于常量值,过去我通常使用“public final”方法。我现在开始使用枚举,并且我正在覆盖 toString() 方法以返回与枚举名称不同的值。

I have some JPA code in which I'm creating a TypedQuery with named parameters, one of which is a String representation of the enum value. If I merely set the parameter using Status.ACTIVE, I get the proper "A" value, but an exception is thrown because it's type is actually Status rather than String. It only works if I explicitly call the toString() method. I thought that simply overriding the toString() method would result in a String type being returned, no matter what the class type was.

我有一些 JPA 代码,我在其中创建了一个带有命名参数的 TypedQuery,其中一个是枚举值的字符串表示。如果我只是使用 Status.ACTIVE 设置参数,我会得到正确的“A”值,但会抛出异常,因为它的类型实际上是 Status 而不是 String。它仅在我显式调用 toString() 方法时才有效。我认为简单地覆盖 toString() 方法会导致返回 String 类型,无论类类型是什么。

This is the enum:

这是枚举:

public enum Status {
    ACTIVE ("A"),
    PENDING ("P"),
    FINISHED ("F");

    private final String value;

    Status(String value) {
        this.value = value;
    }

    public String toString() {
        return value;
    }
};

This is the TypedQuery:

这是 TypedQuery:

    TypedQuery<MechanicTimeEvent> query = entityManager().createQuery("SELECT o FROM MechanicTimeEvent o WHERE o.id.mechanicNumber = :mechanicNumber AND o.id.status = :status", MechanicTimeEvent.class);
    query.setParameter("mechanicNumber", mechanicNumber);
    query.setParameter("status", Status.ACTIVE.toString());

采纳答案by lauwie

Is the field statusof the MechanicTimeEvent bean an enum type? If not, I would suggest to change it to the enum type Status.

statusMechanicTimeEvent bean的字段是枚举类型吗?如果没有,我建议将其更改为 enum type Status

You can annotate it with @Enumerated(EnumType.STRING)

你可以用 @Enumerated(EnumType.STRING)

Furthermore I would suggest to remove the value part of your enum and just use the names like:

此外,我建议删除枚举的值部分,只使用如下名称:

public enum Status {
   ACTIVE,
   PENDING,
   FINISHED;
}

回答by Lazy Beard

public enum Status {
    ACTIVE,
    PENDING,
    FINISHED;

    @Override
    public String toString() {
        String name = "";
        switch (ordinal()) {
        case 0:
            name = "A";
            break;
        case 1:
            name = "P";
            break;
        case 2:
            name = "F";
            break;
        default:
            name = "";
            break;
        }
        return name;
    }
};

回答by java_mouse

If I understand your question correctly, You should do the enum mapping other way around. In this way states are stored as state and JPA would process the enum based on its name A,P, F).

如果我正确理解您的问题,您应该以其他方式进行枚举映射。通过这种方式,状态存储为状态,JPA 将根据其名称 A、P、F 处理枚举。

public enum Status {
    A("ACTIVE"),
    P("PENDING"),
    F("FINISHED");

In this way you can just pass Status without invoking the toString() method to JPA. The .name() method on the ENUM will be invoked automatically to get the status code for persistence.

通过这种方式,您可以只将 Status 传递给 JPA,而无需调用 toString() 方法。ENUM 上的 .name() 方法将被自动调用以获取持久化的状态代码。

回答by Cygnusx1

This or you simply implement a getter for the value:

这或者您只是为该值实现一个getter:

public String getValue()

And you call it in your code:

你在你的代码中调用它:

query.setParameter("status", Status.ACTIVE.getValue());

回答by Jagat

toStringis just an ordinary method in Object that is explicitly called by some methods like PrintStream.println (remember System.out.println) or considered during concatenation using the + operator. Not every method needs to implement this behavior.

toString只是 Object 中的一个普通方法,它被一些方法显式调用,如 PrintStream.println(记住 System.out.println)或在使用 + 运算符连接期间考虑。并非每个方法都需要实现此行为。

I'd suggest you use a more descriptive method name like getValueand call it explicitly instead of override toString

我建议您使用更具描述性的方法名称,例如getValue并显式调用它而不是覆盖toString

回答by zg_spring

java.lang.Enum said clearly:
 /**
 * Returns the name of this enum constant, exactly as declared in its
 * enum declaration.
 * 
 * <b>Most programmers should use the {@link #toString} method in
 * preference to this one, as the toString method may return
 * a more user-friendly name.</b>  This method is designed primarily for
 * use in specialized situations where correctness depends on getting the
 * exact name, which will not vary from release to release.
 *
 * @return the name of this enum constant
 */
 public final String name()

just like the loft say ,you can use "name" method to get the name. also you can use toString() method.

就像阁楼说的那样,您可以使用“名称”方法来获取名称。您也可以使用 toString() 方法。

of course it is just name of this enum constant.

当然,它只是这个枚举常量的名称。