2014-04-21 02:14:48 +00:00
|
|
|
/* Copyright (c) 2008-2014, Avian Contributors
|
2008-02-19 18:06:52 +00:00
|
|
|
|
|
|
|
Permission to use, copy, modify, and/or distribute this software
|
|
|
|
for any purpose with or without fee is hereby granted, provided
|
|
|
|
that the above copyright notice and this permission notice appear
|
|
|
|
in all copies.
|
|
|
|
|
|
|
|
There is NO WARRANTY for this software. See license.txt for
|
|
|
|
details. */
|
|
|
|
|
2007-09-26 17:27:09 +00:00
|
|
|
package java.lang;
|
|
|
|
|
|
|
|
import java.lang.reflect.Method;
|
|
|
|
|
2007-11-14 16:32:36 +00:00
|
|
|
public abstract class Enum<E extends Enum<E>> implements Comparable<E> {
|
2007-09-26 17:27:09 +00:00
|
|
|
private final String name;
|
2011-11-20 02:22:34 +00:00
|
|
|
protected final int ordinal;
|
2007-09-26 17:27:09 +00:00
|
|
|
|
|
|
|
public Enum(String name, int ordinal) {
|
|
|
|
this.name = name;
|
|
|
|
this.ordinal = ordinal;
|
|
|
|
}
|
|
|
|
|
|
|
|
public int compareTo(E other) {
|
2009-08-21 22:06:12 +00:00
|
|
|
if (getDeclaringClass() != other.getDeclaringClass()) {
|
|
|
|
throw new ClassCastException();
|
|
|
|
}
|
|
|
|
|
2007-09-26 17:27:09 +00:00
|
|
|
return ordinal - other.ordinal;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) {
|
2013-02-03 14:39:31 +00:00
|
|
|
if (name == null) throw new NullPointerException("name");
|
|
|
|
if (!enumType.isEnum())
|
|
|
|
throw new IllegalArgumentException(enumType.getCanonicalName() + " is not an enum.");
|
2009-08-13 14:57:58 +00:00
|
|
|
|
|
|
|
try {
|
|
|
|
Method method = enumType.getMethod("values");
|
2010-09-01 16:10:11 +00:00
|
|
|
Enum values[] = (Enum[]) method.invoke(null);
|
2009-08-13 14:57:58 +00:00
|
|
|
for (Enum value: values) {
|
|
|
|
if (name.equals(value.name)) {
|
|
|
|
return (T) value;
|
2007-09-26 17:27:09 +00:00
|
|
|
}
|
|
|
|
}
|
2009-08-13 14:57:58 +00:00
|
|
|
} catch (Exception ex) {
|
2013-02-03 14:39:31 +00:00
|
|
|
// Cannot happen
|
|
|
|
throw new Error(ex);
|
2007-09-26 17:27:09 +00:00
|
|
|
}
|
2009-08-13 14:57:58 +00:00
|
|
|
|
2013-02-03 14:39:31 +00:00
|
|
|
throw new IllegalArgumentException(enumType.getCanonicalName() + "." + name + " is not an enum constant.");
|
2007-09-26 17:27:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public int ordinal() {
|
|
|
|
return ordinal;
|
|
|
|
}
|
2007-09-26 18:59:18 +00:00
|
|
|
|
2008-08-12 22:21:39 +00:00
|
|
|
public final String name() {
|
|
|
|
return name;
|
|
|
|
}
|
|
|
|
|
2007-09-26 18:59:18 +00:00
|
|
|
public String toString() {
|
|
|
|
return name;
|
|
|
|
}
|
2009-06-02 23:14:38 +00:00
|
|
|
|
|
|
|
public Class<E> getDeclaringClass() {
|
|
|
|
Class c = getClass();
|
|
|
|
while (c.getSuperclass() != Enum.class) {
|
|
|
|
c = c.getSuperclass();
|
|
|
|
}
|
|
|
|
return c;
|
|
|
|
}
|
2007-09-26 17:27:09 +00:00
|
|
|
}
|