我如何创建一个通用的枚举器?它将是这个例子中
next()
的通用版本。 public class TestEnum
{
enum Temperature { hot, cold };
public static void main(String[] args)
{
Temperature t = Temperature.hot;
Temperature t2 = next(t);
}
static Temperature next(Temperature t)
{
if (t.ordinal() == Temperature.values().length - 1)
return Temperature.values()[0];
else
return Temperature.values()[t.ordinal() + 1];
}
}
编辑:在评论中,@irreputable
提出了一种更好的解决方案。如果你把它发表为答案,我会选择它。你可能想节省时间,可以复制这个答案。
static <T extends Enum<T>> T next(T t)
{
int index = t.ordinal();
@SuppressWarnings("unchecked")
Enum<T>[] constants = t.getClass().getEnumConstants();
if (index == constants.length - 1)
{
@SuppressWarnings("unchecked")
T result = (T)constants[0];
return result;
}
else
{
@SuppressWarnings("unchecked")
T result = (T)constants[index + 1];
return result;
}
}
@SuppressWarnings("unchecked")
,<T extends Enum<?>>
来定义类型,并明确捕获NoSuchMethodException
、InvocationTargetException
、IllegalAccessException
,如果发生异常,我会抛出RuntimeException
,因为我认为枚举旋转是低风险的。 - H2ONaClClass.getEnumConstants()
。 - irreputable