Groovy enum is very much like enum in Java, and easier to use. There are many Groovy books out there, but none of them explain it very well, so I decide to learn it by doing. This post creates an Eclipse Groovy project and write some examples to illustrate the usage of Groovy enum.
First, let's create a Groovy project:
Then create a package com.makble.testgdk and add two Groovy classes to the package.
ColorEnum.groovy
package com.makble.testgdk; public enum ColorEnum { WHITE('white', 'White is mix of all colors'), BLACK('black', 'Black is no colors'), RED('red', 'Red is the color of blood') final String id; final String desc; static final Map map static { map = [:] as TreeMap values().each{ color -> println "id: " + color.id + ", desc:" + color.desc map.put(color.id, color) } } private ColorEnum(String id, String desc) { this.id = id; this.desc = desc; } static getColorEnum( id ) { map[id] } }
MainTest.groovy
package com.makble.testgdk println ColorEnum.values().size() println ColorEnum.getColorEnum('white') println ColorEnum.WHITE.desc // values return array of all enums defined in ColorEnum println ColorEnum.values().getClass()
The package explorer
Press Alt + Shift + X, G to run the MainTest Groovy script:
3 WHITE White is mix of all colors class [Lcom.makble.testgdk.ColorEnum;
In the enum static block, all enums were added to a map, the key is the id of the enum. Method getColorEnum can retrieve the description of the enum by its id.
The values() method returns an array of all enums defined in enum class.
You may wonder where this method was defined, you will not find it in class hierarchy. This method was defined by EnumVisitor, the class was generated dynamically and some methods and properties were added to the class, include the values() method.
The class is generated in org.codehaus.groovy.classgen.EnumVisitor.