Storing EnumSet in a database?

前端 未结 10 1813
借酒劲吻你
借酒劲吻你 2020-12-03 21:24

So in C++/C# you can create flags enums to hold multiple values, and storing a single meaningful integer in the database is, of course, trivial.

In Java you have Enu

10条回答
  •  旧巷少年郎
    2020-12-03 21:54

    // From Adamski's answer
    public static > int encode(EnumSet set) {
        int ret = 0;
    
        for (E val : set) {
            ret |= 1 << val.ordinal();
        }
    
        return ret;
    }
    
    @SuppressWarnings("unchecked")
    private static > EnumSet decode(int code,
            Class enumType) {
        try {
            E[] values = (E[]) enumType.getMethod("values").invoke(null);
            EnumSet result = EnumSet.noneOf(enumType);
            while (code != 0) {
                int ordinal = Integer.numberOfTrailingZeros(code);
                code ^= Integer.lowestOneBit(code);
                result.add(values[ordinal]);
            }
            return result;
        } catch (IllegalAccessException ex) {
            // Shouldn't happen
            throw new RuntimeException(ex);
        } catch (InvocationTargetException ex) {
            // Probably a NullPointerException, caused by calling this method
            // from within E's initializer.
            throw (RuntimeException) ex.getCause();
        } catch (NoSuchMethodException ex) {
            // Shouldn't happen
            throw new RuntimeException(ex);
        }
    }
    

提交回复
热议问题