请注意,您的问题混合了两个不同的问题:将枚举传递给函数或将枚举常量传递给函数。我的理解是你想传递枚举本身,而不是它的常量之一给函数。如果不是:请参阅 Narendra Pathai 关于如何将单个枚举常量传递给函数的答案。如果您不知道枚举和枚举常量之间的区别是什么,请查看docs 关于枚举...
我知道您想要的是拥有一个打印(或任何其他)函数,您可以在其中传递任何可能的枚举,以打印每个枚举的可能值(即常量)。我找到了以下两种方法来做到这一点:
假设我们有以下枚举:
// The test enum, any other will work too
public static enum ETest
{
PRINT,MY,VALUES
}
变体 1: 将常量数组从您的枚举传递给您的函数;由于枚举的常量是静态值,因此可以轻松访问它们并将其传递给您的“打印”函数,如下所示:
public static void main(String[] args)
{
// retreive all constants of your enum by YourEnum.values()
// then pass them to your function
printEnum(ETest.values());
}
// print function: type safe for Enum values
public static <T extends Enum<T>> void printEnum(T[] aValues)
{
System.out.println(java.util.Arrays.asList(aValues));
}
变体 2: 将枚举的类作为函数参数传递。这可能看起来更漂亮,但请注意其中涉及反射(性能):
public static void main(String[] args)
{
printEnum2(ETest.class);
}
// print function: accepts enum class and prints all constants
public static <T extends Enum<T>> void printEnum2(Class<T> aEnum)
{
// retreive all constants of your enum (reflection!!)
System.out.println(java.util.Arrays.asList(aEnum.getEnumConstants()));
}
在我看来,最好使用 variante 1,因为在 variante 2 中过度使用了反射。variante 2 给您的唯一优势是您拥有 Enum 本身的 Class 对象(静态枚举,不仅它是常量)在你的函数中,所以我已经提到它的完整性。