0

我想做这样的事情:

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); 
4

3 回答 3

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, ... });
于 2012-11-09T02:17:00.573 回答
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

于 2012-11-09T03:08:10.253 回答
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);
于 2012-11-09T02:28:46.687 回答