如何在Java方法中将枚举作为参数传递? [英] How to pass enum as an argument in a method in java?
问题描述
public class Enumvalues{
enum courseList {
JAVA,
C,
PYTHON,
PERL
}
enum generalInformation {
NAME,
AGE,
PHONE
}
enum sex {
MALE,
FEMALE
}
}
public static void main(String args[]) {
printEnumValue(generalInformation); // how to pass enum in this block
}
static void printEnumValue(enum generalInformation) { // how to receive enum in this block
System.out.println(java.util.Arrays.asList(generalInformation.values()));
}
推荐答案
枚举是一个类。因此,您可以传递类的实例(例如, EnumValues.generalInformation.PHONE
),也可以传递类本身(例如, EnumValues.generalInformation。类
)。
An enum is a class. So you can pass an instance of the class (EnumValues.generalInformation.PHONE
for example), or you can pass the class itself (EnumValues.generalInformation.class
for example).
如果要列出枚举类的所有实例,则需要传递枚举类并使用例如, EnumSet.allOf(EnumValues.generalInformation.class)
。
If you want to list all the instances of an enum class, you need to pass the enum class, and use EnumSet.allOf(EnumValues.generalInformation.class)
for example.
您的困惑主要来自以下事实:不遵守Java命名约定。枚举是类,应以大写字母开头(例如, GeneralInformation
)。混淆的另一个原因是名称的错误选择。 JAVA不是课程列表。这是一门课程。因此,枚举应命名为 Course
。
Your confusion principally comes from the fact that you don't respect the Java naming conventions. ENums are classes and should start with an upper-case letter (GeneralInformation
for example). An other source of confusion is the bad choice of names. JAVA is not a course list. It's a course. So the enum should be named Course
.
这篇关于如何在Java方法中将枚举作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!