Java Enum行为

时间:2009-12-04 16:02:17

标签: java enums

我们有以下列举:

public enum ComponentTypes {

    PDIFF(301),
    TDIFF(302),
    TADJ(303);

    private long componentTypeId;

    private ComponentTypes(long componentTypeId){
        this.componentTypeId = componentTypeId;
    }

    public Long getId(){
        return this.componentTypeId;
    }
}

在我们的某个测试设置中,我们执行c.setComponentTypeId(ComponentTypes.TADJ.getId())但是在测试中调用c.getComponentTypeId()时,它会抛出NullPointerException,但c.setComponentTypeId(303L)按预期工作。使用枚举来设置值时我错过了什么?

修改

看起来@Tom直接与long / Long不一致。现在,getId()返回long而不是Long,它按预期工作。

修改

看起来我刚才所说的错误 autoboxing按预期工作在刷新系统jvm等之后没问题 - 这对我没有任何意义!

3 个答案:

答案 0 :(得分:1)

你没有说“c”是什么类型,但是我怀疑它的setter没有按你认为的那样做 - NullPointerException表示自动拆箱出错了。虽然成员Long时返回long是代码气味,但您枚举本身似乎没有问题。

实际上,使用枚举ID调用c.setComponentTypeId()是另一种代码气味。你为什么不使用枚举本身,c.setComponentType()?你这样做的方式几乎失去了你所有的枚举价值。

答案 1 :(得分:0)

您在测试中说您调用了setComponentId,但是您没有包含此方法的源代码。你可以粘贴它,还可以显示如何创建测试中的'c'对象吗?

Tom,如果他们使用的是最近支持autoboxing的java版本肯定很长/ Long会无关紧要吗?

答案 2 :(得分:0)

你在哪里初始化c?我怀疑这是问题,你收到的NullPointerException实际上来自setComponentTypeId调用,而不是getter。

使用你的代码进行枚举(没有修改)我运行了以下内容:

ComponentTypes c = ComponentTypes.PDIFF;
c.setComponentTypeId(ComponentTypes.TADJ.getId());
System.out.println(c.getComponentTypeId());

c.setComponentTypeId(303L);
System.out.println(c.getComponentTypeId());

我的输出:

  

303

     

303

然而;如果c未正确初始化,则在第一次尝试调用c.setComponentTypeId时会出现NullPointerException。