如何将枚举传递给构造函数?

时间:2012-11-09 02:12:25

标签: java constructor enums arguments

我想做这样的事情:

public class MyEnumTest {

    public enum MyEnum;
    private MyEnum value;

    public MyEnumTest(enum e)
    {
        this.MyEnum = e; 
        this.value = this.MyEnum.values[0]//Set value to the first enum value.
    }

    public void setValue(MyEnum e)
    {
        this.value = e; 
    }

    public MyEnum getValue()
    {
        return value;
    }

}

并称之为:

MyEnumTest car = new MyEnumTest({HONDA, FORD, TOYOTA, HOLDEN}); 
MyEnumTest fruit = new MyEnumTest({APPLE, BANANA, CHERRY}); 

/* some operations occur*/ 

if (car.getValue() == car.FORD) System.out.println("Vrooom!"); 
if (fruit.getValue()) == fruit.APPLE) System.out.println ("Is red and round and delicious"); 

这样做有什么想法吗?

对于奖励标记 - 是否可以使用枚举值设置初始值? 例如

之类的东西
MyEnumTest myET = new myEnumTest(new enum {RED, GREEN, BLUE, YELLOW}, BLUE); 

3 个答案:

答案 0 :(得分:6)

您可以使用(不使用enum关键字):

public MyEnumTest(MyEnum e)
{
    this.myEnum = e; 
    this.value = MyEnum.values()[0];
}

对于第2部分,您可以定义重载的构造函数:

public MyEnumTest(MyEnum[] myEnums) {

并使用:

MyEnumTest myET = new MyEnumTest(new MyEnum[] { MyEnum.FOO, ... });

答案 1 :(得分:3)

正如其他人所说,很难理解你想要做什么,但这是我最好的猜测:

public enum Color {
    RED, GREEN, YELLOW, BLUE;
}


public class MyEnumTest<E extends Enum<E>> {
    private final Class<E> enumType;
    private final E value; 

    public Class<E> getEnumType() {
        return enumType;
    }

    public E getValue() {
        return value;
    }

    public MyEnumTest(Class<E> enumType, E value) {
        this.enumType = enumType;
        this.value = value;
    }

    public MyEnumTest(Class<E> enumType) {
        this(enumType, enumType.getEnumConstants()[0]);
    }

    public static void main(String... args) {
        // no initial value provided
        MyEnumTest<Color> myET = new MyEnumTest<Color>(Color.class);
        if (myET.getValue() == Color.RED) {
            System.out.println("It's probably an apple");
        }

        // providing an initial value
        myET = new MyEnumTest<Color>(Color.class, Color.YELLOW);
        if (myET.getValue() == Color.YELLOW) {
            System.out.println("It's probably a banana");
        }
    }
}

另外,请记住,枚举值是静态的...所以,像myET.MyEnum.RED这样的东西没有意义......你应该使用:Color.RED

答案 2 :(得分:1)

很难说出你想要做什么。 Reimeus的答案显示了如何处理您的特定MyEnum作为参数。如果要将类实现为使用任何枚举,请使用以下命令:

public class MyEnumTest<E extends Enum<E>> {

    private final E firstValue;

    public MyEnumTest(Class<E> enumType)
    {
        this.firstValue = enumType.getEnumConstants()[0];
    }

    ...
}

并像这样实例化:

MyEnumTest myET = new myEnumTest(MyEnum.class);