简体   繁体   English

Java枚举重写toString()

[英]Java enum overriding toString()

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. 我之前从未真正使用Java枚举类来获取常量值,我过去通常使用“公共最终”方法。 I've started using an enum now and I'm overriding the toString() method to return a different value than the enum name. 我现在开始使用枚举,并且我重写了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. 我有一些JPA代码,我在其中创建一个带有命名参数的TypedQuery,其中一个是枚举值的String表示。 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. 如果我只使用Status.ACTIVE设置参数,我会得到正确的“A”值,但会抛出异常,因为它的类型实际上是Status而不是String。 It only works if I explicitly call the toString() method. 它只有在我显式调用toString()方法时才有效。 I thought that simply overriding the toString() method would result in a String type being returned, no matter what the class type was. 我认为简单地重写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());
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;
    }
};

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. 通过这种方式,您可以在不调用toString()方法的情况下传递Status到JPA。 The .name() method on the ENUM will be invoked automatically to get the status code for persistence. 将自动调用ENUM上的.name()方法以获取持久性的状态代码。

Is the field status of the MechanicTimeEvent bean an enum type? MechanicTimeEvent bean的字段status是枚举类型吗? If not, I would suggest to change it to the enum type Status . 如果没有,我建议将其更改为枚举类型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;
}

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());

toString is 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. toString只是Object中的一个普通方法,由PrintStream.println(记住System.out.println)等一些方法显式调用,或者在使用+运算符连接时考虑。 Not every method needs to implement this behavior. 并非每种方法都需要实现此行为。

I'd suggest you use a more descriptive method name like getValue and call it explicitly instead of override toString 我建议你使用更具描述性的方法名称,如getValue ,并显式调用它而不是覆盖toString

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. 当然它只是这个枚举常量的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM