Last active
April 6, 2017 13:58
-
-
Save LuxXx/22f32287cd1d2a472a7ed94aa6ab4b78 to your computer and use it in GitHub Desktop.
What is actually an enum? It is actually just a class.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* I wanted to understand the inner of an enum better, therefore I tried to build my own enumeration class | |
* that does exactly the same | |
* This code equals to | |
* public enum Enum { | |
* A, B, C; | |
* } | |
*/ | |
import java.lang.reflect.Field; | |
public class CEnum implements Comparable<CEnum> { | |
public static final CEnum A = new CEnum(); | |
public static final CEnum B = new CEnum(); | |
public static final CEnum C = new CEnum(); | |
/* ... */ | |
private static final CEnum[] values; | |
static { | |
Field[] fields = CEnum.class.getFields(); | |
values = new CEnum[fields.length]; | |
for (int i = 0; i < fields.length; i++) { | |
try { | |
values[i] = (CEnum) fields[i].get(null); | |
} catch (IllegalArgumentException e) { | |
e.printStackTrace(); | |
} catch (IllegalAccessException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
public static CEnum valueOf(Class<CEnum> enumType, String name) { | |
return valueOf(name); | |
} | |
public static CEnum valueOf(String arg0) { | |
if (arg0 == null) | |
throw new NullPointerException("Name is null"); | |
for (CEnum cEnum : values) { | |
if (arg0.equals(cEnum.name())) | |
return cEnum; | |
} | |
throw new IllegalArgumentException("No enum constant " + CEnum.class.getName() + "." + arg0); | |
} | |
public static CEnum[] values() { | |
return values; | |
} | |
public String name() { | |
return CEnum.class.getFields()[ordinal(this)].getName(); | |
} | |
@Override | |
public String toString() { | |
return name(); | |
} | |
private static int ordinal(CEnum o) { | |
int ordinal = 0; | |
for (int i = 0; i < values.length; i++) { | |
if (values[i] == o) ordinal = i; | |
} | |
return ordinal; | |
} | |
public int ordinal() { | |
return ordinal(this); | |
} | |
@Override | |
public int compareTo(CEnum o) { | |
if (this == o) return 0; | |
return ordinal(this) < ordinal(o) ? -1 : 1; | |
} | |
public Class<CEnum> getDeclaringClass() { | |
return CEnum.class; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment