Skip to content

Instantly share code, notes, and snippets.

@166MMX
Created March 29, 2019 11:17
Show Gist options
  • Save 166MMX/3f5d3011d70654a3c8e99f7f971c5f6c to your computer and use it in GitHub Desktop.
Save 166MMX/3f5d3011d70654a3c8e99f7f971c5f6c to your computer and use it in GitHub Desktop.
Poor Man's Enum
import groovy.transform.EqualsAndHashCode
@EqualsAndHashCode
class FooType {
private static final Map<String, FooType> nameMap = [:]
private static final Map<String, FooType> identifierMap = [:]
private static final Set<FooType> values = []
final String name
static final FooType A = new FooType('A', 'a')
static final FooType B = new FooType('B','b')
protected FooType(String identifier, String name) {
this.name = name
if (identifierMap.containsKey(identifier)) {
throw new IllegalArgumentException("Identifier already taken")
}
values << this
nameMap[name] = this
identifierMap[identifier] = this
}
static Set<FooType> values() {
Collections.unmodifiableSet(values)
}
static FooType valueOf(String identifier) {
def result = identifierMap[identifier]
if (result == null) {
throw new IllegalArgumentException("${this.class.simpleName} type has no constant with the specified identifier.")
}
result
}
static FooType fromName(String name) {
nameMap[name]
}
}
@EqualsAndHashCode
class BarType extends FooType {
private static final Map<String, BarType> nameMap = [:]
private static final Map<String, BarType> identifierMap = [:]
private static final Set<BarType> values = []
static final BarType C = new BarType('C', 'c')
protected BarType(String identifier, String name) {
super(identifier, name)
values << this
nameMap[name] = this
identifierMap[identifier] = this
}
static Set<BarType> values() {
Collections.unmodifiableSet(values)
}
static BarType valueOf(String identifier) {
def result = identifierMap[identifier]
if (result == null) {
throw new IllegalArgumentException("${this.class.simpleName} type has no constant with the specified identifier.")
}
result
}
static BarType fromName(String name) {
nameMap[name]
}
}
Map<FooType, Object> asd = [:]
asd[BarType.C] = ''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment