user2247776
user2247776

Reputation:

how to fetch name from enum in java

I do have a enum class in java as follows

public enum SMethod {

/**
 * LEAVE IN THIS ORDER
 */
A    (true, true, true,false),
B    (true, true, false,false),
C    (true, true, false,false),
D    (false, false, false)

} 

Another class have below method

private String getSMethod(boolean isSds) {
    if (isClsSds)
        return "A";
    else 
        return "B";
}

Currently this method return hard code value but string.But I want to return it using SMethod enum.I have written it as follows:

private SMethod getSMethod(boolean isSds) {
    if (isClsSds)
        return SMethod.A;
    else 
        return SMethod.B;
}

but my need is this method should return String.

Upvotes: 1

Views: 150

Answers (3)

Sri Harsha Chilakapati
Sri Harsha Chilakapati

Reputation: 11940

There are two ways.

So you can use

public String getName(SMethod enm)
{
    return enm.name();
    // or enm.toString();
}

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 121998

return SMethod.A.name(); will return string

see name() method

Returns the name of this enum constant, exactly as declared in its enum declaration.

Upvotes: 2

BobTheBuilder
BobTheBuilder

Reputation: 19284

Use name() method:

return SMethod.A.name();

To get the String name of the enum object.

Upvotes: 2

Related Questions