javaunit-testingsizeofbitmaskmemory-size

Programatically calculate the size of a value type


I'm writing a unit test for a method that packs boolean values into a byte. The various bit locations are determined by the value of an enum, which only has 5 values right now, but it's conceivable (though extremely unlikely) that this number could go to 9.

I'd like a simple test along the lines of:

private byte m_myNum; enum MyEnum {...}

assert(sizeof(m_myNum) <= MyEnum.values().length);

I'm under the impression that there's not a sizeof function in Java. What's the most elegant workaround?

---EDIT

I don't think I was clear. I'm not concerned about normal runtime. My issue is that I can write this code now with a byte that stores all the information, but as the Enum grows in an unrelated part of code, I could reach a point where my bitmasking code breaks. Rather than having this in a deployed application, I'd like to have a unit test that fails when the number of states in the enum exceeds the number of bits in the storage variable, so when a programmer adds that ninth enum, they can adjust the type of the variable to something with more than eight bits.


Solution

  • I think this test does what you want. It is probably a waste of your time to get more generic than this.

    public void testEnumSizeLessThanOneByte() throws Exception 
    { 
        assertTrue("MyEnum must have 8 or less values.", 
                    MyEnum.values().length <= 8);
    }