How to pass enum as an argument in a method in java?
Note that your question has mixed up two different problems: Passing an Enum to a function OR Passing an Enum constant to a function. My understanding was that you want to pass the enum itself, not one of it’s constants to the function. If not: refer to Narendra Pathai’s answer on how to pass a single enum constant to a function. If you don’t know what the difference between an enum and an enum constant is, review the docs about enums.
I Understand that what you want is to have a print (or any other) function where you can pass any possible enum, to print each of the enum’s possible values (i.e. constants). I’ve found the following two approaches to do this:
Lets say we have the following enum:
// The test enum, any other will work too public static enum ETest
Variante 1: Pass the array of constants from your enum to your function; As the enum’s constants are static values, they can easily be accessed and passed to your ‘print’ function as follows:
public static void main(String[] args) < // retreive all constants of your enum by YourEnum.values() // then pass them to your function printEnum(ETest.values()); >// print function: type safe for Enum values public static > void printEnum(T[] aValues)
Variante 2: Pass the enum’s class as function parameter. This might look more beautiful, but be aware that reflection is involved (performance):
public static void main(String[] args) < printEnum2(ETest.class); >// print function: accepts enum class and prints all constants public static > void printEnum2(Class aEnum) < // retreive all constants of your enum (reflection!!) System.out.println(java.util.Arrays.asList(aEnum.getEnumConstants())); >
In my opinion, it’s better to use variante 1 because of the overuse of reflection in variante 2. The only advantage that variante 2 gives you, is that you have the Class object of the Enum itself (the static enum, not only it’s constants) inside your function, so I’ve mentioned it for completeness.
Параметры в enum java
* Информация для продвинутых юзеров. На самом деле возможно ограниченное наследование от Enum. Подробнее здесь: https://kibungo.livejournal.com/19999.html Пример наследования и переопределения общего метода:
public enum MyEnum < VAL1 < public int returnMyVal()< return 20; >>, VAL2; public int returnMyVal() < return 10; >> ------------------------ System.out.println(MyEnum.VAL1.returnMyVal()) // 20 System.out.println(MyEnum.VAL2.returnMyVal()) // 10
«По сравнению с обычными классами, на Enum наложили одно серьезное ограничение — от него невозможно наследоваться.» Что за бред вы пишете?! Все перечисления изначально неявно расширяют класс java.lang.Enum, а поскольку в Java нету множественного наследования, то и расширять enum уже больше ничего не может.
В статье enum в коде с маленькой буквы, в комментариях к коду — Enum с большой Почему не говорится, что это разные вещи? Если у нас несколько enum`ов с перечислениями в приложении и нам нужно передать один из них как аргумент в метод можно сделать просто так someMethod(Enum e) < и здесь написать условие для выбора одного из enum`ов >Т.е. не нужно приводить все enum`ы к единому интерфейсу или абстрактному классу, чтобы выбрать один из enum`ов Как я понял Enum(тот который с большой буквы) — это что-то типа пустого интерфейса для всех enum`ов
@Override public String toString() < return "DayOfWeek';
В коде приведенного примера про школьника есть ошибка: задано поле private ScholarSchedule schedule, но сеттер для него не прописан, а так как оно изначально не инициализировано, получаете NullPointerException. Добавьте сеттер (либо просто сделайте это поле public, что есть костыль) для задания значения:
public void setSchedule(ScholarSchedule schedule)
Ну или, в конце концов, поместите метод main в класс Scholar (видимо так и задумывалось автором примера изначально), тогда он будет иметь доступ к private ScholarSchedule schedule и сможет инициализировать его надлежащим образом.
How to define properties for Enum items
I have read the question Difference of Enum between java and C++? but I'm still confused. I would like the following to return the related String:
From what I have read, this should be possible. Just would like you to shed some light on it on how to implement it.
2 Answers 2
Short Answer
You need a constructor, a field and a getter.
Constructors
Enum types can have constructors, provided that their access level is either private or default (package-private). You can not directly call these constructors, except in the enum declaration itself. Similar to classes, when you define an enum constant without parameters, you actually call the default constructor generated by the compiler. E.g.
And just like in classes, if you define an explicit constructor, the compiler will not insert a default constructor, so this will not compile:
This is a pretty good reference on enums that also explains the constructor issues.
Fields and Accessors
Enums are constants and are immutable as such. They can however define fields, that can have state. This is an awful practice, because developers will expect enums and their associated values to be constants, but you can still define a non-final field in an enum with getters and setters.
public enum Color < RED("FF0000"), GREEN("00FF00"), BLUE("0000FF"); private String code; public String getCode()public void setCode(String code) private Color(String code) >
But it enables evil code like this:
String oldBlue = Color.BLUE.getCode(); Color.BLUE.setCode(Color.RED.getCode()); Color.RED.setCode(oldBlue);
So in 99.99 % of cases: if you have fields in your enums, you should make them final and provide getters only. If the fields are not immutable themselves, provide defensive copies:
public enum Band < THE_BEATLES("John","Paul","George","Ringo"); private final Listmembers; public List getMembers()< // defensive copy, because the original list is mutable return new ArrayList(members); > private Band(String. members) < this.members=Arrays.asList(members); >>
Solution
In your case it's very simple: you just need a single field of type string (immutable), so initializing it in the constructor and providing a getter is perfectly ok:
public enum Checker < EMPTY ("Empty"), RED ("Red"), YELLOW ("Yellow"); private final String value; private Checker(final String value) < this.value = value; >public String getValue() < return value; >>