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