Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java Enum valueOf has two parameters?

Tags:

java

enums

Why does valueOf have two parameters?

in Java documentation for valueOf

public static <T extends Enum<T>> T valueOf​(Class<T> enumType, String name)

Parameters:

enumType - the Class object of the enum type from which to return a constant

name - the name of the constant to return

But most examples I read online says:

enum WorkDays {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY;
}

Test:

WorkDays day1 = WorkDays.valueOf("MONDAY");
System.out.println(day1); // >>>  MONDAY

It seems that the method used only one parameter?

like image 849
jxie0755 Avatar asked Mar 20 '19 16:03

jxie0755


People also ask

Can enum have 2 values?

The Enum constructor can accept multiple values.

Can an enum have two values Java?

Learn to create Java enum where each enum constant may contain multiple values. We may use any of the values of the enum constant in our application code, and we should be able to get the enum constant from any of the values assigned to it.

How does enum valueOf work in Java?

valueOf. Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)

Can I override valueOf enum Java?

Since you cannot override valueOf method you have to define a custom method ( getEnum in the sample code below) which returns the value that you need and change your client to use this method instead. getEnum could be shortened if you do the following: v. getValue().


1 Answers

As you indicated in previous comments that you find the text in the documentation confusing, and since your profile indicates you are a novice programmer:

Enum is the superclass of all enums you will declare. In your example, WorkDays can be seen as a specific case of the Enum class. The valueOf() static method documentation is writen for this parent Enum class. Meaning that in your case, it would be called as: Enum.valueOf(WorkDays.class, "MONDAY").

Now, since you made your own Enum (i.e. WorkDays), you don't need to use this static parent method. You can just use the method that is exposed by your self-created enum.

WorkDays.valueOf("Monday")

This is "implicitly declared" meaning that there it will be there for every one of your self-created enums.

like image 112
Stijn Dejongh Avatar answered Oct 06 '22 01:10

Stijn Dejongh