BitSet

public static > int encode(EnumSet set) {
    int ret = 0;

    for (E val : set) {
        ret |= 1 << val.ordinal();
    }

    return ret;
}

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) {
        throw new RuntimeException(ex);
    } catch (InvocationTargetException ex) {
        throw (RuntimeException) ex.getCause();
    } catch (NoSuchMethodException ex) {
        throw new RuntimeException(ex);
    }
}

你可能感兴趣的:(BitSet)