开发者

Java Enum behavior

We have the following enumeration:

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;
    }
}

In one of our tests setup we do c.setComponentTypeId(ComponentTypes.TADJ.getId()) but when c.getComponentTypeId() is invoked in the test it throws NullPointerException, yet c.setComponentTypeId(303L) works as expected. What am I missing with use of the enum to set the value?

EDIT

Looks like @Tom was straight on with the long/Long inconsistency. Now that getId() returns long not Long it works as expected.

EDIT

Looks like what I said earlier was wrong autoboxing does work there as expected is no issue after I refreshed the system jvm etc -- whi开发者_开发问答ch doesn't make any sense to me!


You don't say what type "c" is, but I suspect its setter is not doing what you think it is -- the NullPointerException is an indication of auto-unboxing gone wrong. You enum itself doesn't appear to have an issue, although returning a Long when the member is long is a code smell.

Actually, calling c.setComponentTypeId() with the enum's ID is another code smell. Why aren't you using the enum itself, with c.setComponentType()? The way you're doing it pretty much loses you all the value of enums.


You say in the test you call setComponentId, but you have not included the source for this method. Can you paste this, and also show how the 'c' object in the test is created?

Tom, if they are using a version of recent java supporting autoboxing surely long/Long won't matter?


Where are you initializing c? I suspect this is the issue and that the NullPointerException you're receiving is actually coming from the setComponentTypeId call not the getter.

Using your code for the enum (with no modifications) I ran the following:

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

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

My Output:

303

303

However; If c is not initialized properly, you get a NullPointerException when you attempt to call c.setComponentTypeId for the first time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜