Get enum by its inner field

后端 未结 5 1339
清歌不尽
清歌不尽 2020-11-27 15:48

Have enum with inner fields, kind of map.

Now I need to get enum by its inner field.

Wrote this:

package test;

/**
 * Test enum to test enum         


        
5条回答
  •  没有蜡笔的小新
    2020-11-27 16:40

    One solution is to add

    public final Test[] TESTS = { null, ONE, TWO, THREE };
    
    public static Test getByNumber(int i) {
        return TESTS[i];
    }
    

    To the enum.

    If the internal data is not an integer, you could have a Map which you populate in a static { ... } initializer. This map could later be used in the getByNumber method above.

提交回复
热议问题