javasun-codemodel

How to generate int field with hex constant vale with codeModel


I am attempting to generate java enums using compile group: 'com.sun.codemodel', name: 'codemodel', version: '2.6'

Each enum constant has two int arguments that must be set to hex/unicode values.

The code I wish to generate will resemble this

public enum MY_ENUM {

    VALUE_0000(0x00, 0x0000),
    VALUE_0001(0x01, 0x0001),
    VALUE_0002(0x02, 0x0002),
    VALUE_0003(0x03, 0x0003);

    private final int first;
    private final int second;

    private MY_ENUM(final int first, final int second) {
        this.first = first;
        this.second = second;
    }

    public int get_first() {
        return first;
    }

    public int get_second() {
        return second;
    }

}

Currently all I can generate is this

public enum MY_ENUM {

    VALUE_0000("0x00", "0x0000"),
    VALUE_0001("0x01", "0x0001"),
    VALUE_0002("0x02", "0x0002"),
    VALUE_0003("0x03", "0x0003");

    private final int first;
    private final int second;

    private MY_ENUM(final int first, final int second) {
        this.first = first;
        this.second = second;
    }

    public int get_first() {
        return first;
    }

    public int get_second() {
        return second;
    }

}

The codeModel code I am employing to generate each constant is this:-

final String[] rawTextDataParts = rawTextDataLine.split(",");

JEnumConstant enumConst = jDefinedClass.enumConstant(generateEnumConstantName(rawTextDataParts[4]));
enumConst.arg(JExpr.lit(rawTextDataParts[0]));
enumConst.arg(JExpr.lit(rawTextDataParts[1]));

I understand that its my use of com.sun.codemodel.JExpr method

public static JExpression lit(String s)

that cause the issue, however I cannot see how to generate the require integer constant from the hex value.

Is it possible to achieve my desired result?

UPDATE

I have the following input data that is driving my code generation

0x00,   0x0000,  VALUE_0000
0x01,   0x0001,  VALUE_0001
0x02,   0x0002,  VALUE_0002
0x03,   0x0003,  VALUE_0003

Solution

  • You don't need to code your numbers as hex constants. Plain ints will do, ie

    VALUE_0000(0,0) // identical to VALUE_0000(0x00, 0x0000)
    

    Try this:

    enumConst.arg(JExpr.lit(Integer.parseInt(rawTextDataParts[0].replaceAll("0x",""))));
    enumConst.arg(JExpr.lit(Integer.parseInt(rawTextDataParts[1].replaceAll("0x",""))));