Skip to content

Method: convertToAxiomValue(Enum)

1: /*
2: * JOPA
3: * Copyright (C) 2024 Czech Technical University in Prague
4: *
5: * This library is free software; you can redistribute it and/or
6: * modify it under the terms of the GNU Lesser General Public
7: * License as published by the Free Software Foundation; either
8: * version 3.0 of the License, or (at your option) any later version.
9: *
10: * This library is distributed in the hope that it will be useful,
11: * but WITHOUT ANY WARRANTY; without even the implied warranty of
12: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13: * Lesser General Public License for more details.
14: *
15: * You should have received a copy of the GNU Lesser General Public
16: * License along with this library.
17: */
18: package cz.cvut.kbss.jopa.oom.converter;
19:
20: import cz.cvut.kbss.jopa.exception.InvalidEnumMappingException;
21:
22: /**
23: * Built-in converter for mapping to/from enum-valued attributes.
24: * <p>
25: * This converter transforms enum constants to/from their ordinal number. It is used for enumerated attributes with
26: * {@link cz.cvut.kbss.jopa.model.annotations.EnumType#ORDINAL} configuration.
27: *
28: * @param <E> Enum type
29: */
30: public class OrdinalEnumConverter<E extends Enum<E>> implements ConverterWrapper<E, Object> {
31:
32: private final Class<E> enumType;
33:
34: public OrdinalEnumConverter(Class<E> enumType) {
35: this.enumType = enumType;
36: }
37:
38: @Override
39: public Object convertToAxiomValue(E value) {
40:• assert value != null;
41: return value.ordinal();
42: }
43:
44: @Override
45: public E convertToAttribute(Object value) {
46: assert value instanceof Number;
47: final int ordinal = ((Number) value).intValue();
48: if (ordinal >= enumType.getEnumConstants().length) {
49: throw new InvalidEnumMappingException("Value " + ordinal + " is not a valid ordinal in " + enumType);
50: }
51: return enumType.getEnumConstants()[ordinal];
52: }
53:
54: @Override
55: public boolean supportsAxiomValueType(Class<?> type) {
56: return Integer.class.isAssignableFrom(type) || Short.class.isAssignableFrom(type) || Byte.class
57: .isAssignableFrom(type);
58: }
59: }