Search in sources :

Example 1 with GenericMapTypeHandler

use of org.terasology.persistence.typeHandling.coreTypes.GenericMapTypeHandler in project Terasology by MovingBlocks.

the class MapTypeHandlerFactory method create.

@SuppressWarnings("unchecked")
@Override
public <T> Optional<TypeHandler<T>> create(TypeInfo<T> typeInfo, TypeHandlerContext context) {
    if (!Map.class.isAssignableFrom(typeInfo.getRawType())) {
        return Optional.empty();
    }
    Type keyType = ReflectionUtil.getTypeParameterForSuper(typeInfo.getType(), Map.class, 0);
    Type valueType = ReflectionUtil.getTypeParameterForSuper(typeInfo.getType(), Map.class, 1);
    if (valueType == null) {
        LOGGER.error("Map is not parameterized and cannot be serialized");
        return Optional.empty();
    }
    Optional<TypeHandler<?>> declaredValueTypeHandler = context.getTypeHandlerLibrary().getTypeHandler(valueType);
    TypeInfo<?> valueTypeInfo = TypeInfo.of(valueType);
    @SuppressWarnings("unchecked") TypeHandler<?> valueTypeHandler = new RuntimeDelegatingTypeHandler(declaredValueTypeHandler.orElse(null), valueTypeInfo, context);
    if (String.class.equals(keyType)) {
        return Optional.of((TypeHandler<T>) new StringMapTypeHandler<>(valueTypeHandler));
    } else {
        Optional<TypeHandler<?>> declaredKeyTypeHandler = context.getTypeHandlerLibrary().getTypeHandler(keyType);
        TypeInfo<?> keyTypeInfo = TypeInfo.of(keyType);
        @SuppressWarnings("unchecked") TypeHandler<?> keyTypeHandler = new RuntimeDelegatingTypeHandler(declaredKeyTypeHandler.orElse(null), keyTypeInfo, context);
        return Optional.of((TypeHandler<T>) new GenericMapTypeHandler<>(keyTypeHandler, valueTypeHandler));
    }
}
Also used : StringMapTypeHandler(org.terasology.persistence.typeHandling.coreTypes.StringMapTypeHandler) Type(java.lang.reflect.Type) GenericMapTypeHandler(org.terasology.persistence.typeHandling.coreTypes.GenericMapTypeHandler) TypeHandler(org.terasology.persistence.typeHandling.TypeHandler) GenericMapTypeHandler(org.terasology.persistence.typeHandling.coreTypes.GenericMapTypeHandler) RuntimeDelegatingTypeHandler(org.terasology.persistence.typeHandling.coreTypes.RuntimeDelegatingTypeHandler) StringMapTypeHandler(org.terasology.persistence.typeHandling.coreTypes.StringMapTypeHandler) Map(java.util.Map) RuntimeDelegatingTypeHandler(org.terasology.persistence.typeHandling.coreTypes.RuntimeDelegatingTypeHandler)

Aggregations

Type (java.lang.reflect.Type)1 Map (java.util.Map)1 TypeHandler (org.terasology.persistence.typeHandling.TypeHandler)1 GenericMapTypeHandler (org.terasology.persistence.typeHandling.coreTypes.GenericMapTypeHandler)1 RuntimeDelegatingTypeHandler (org.terasology.persistence.typeHandling.coreTypes.RuntimeDelegatingTypeHandler)1 StringMapTypeHandler (org.terasology.persistence.typeHandling.coreTypes.StringMapTypeHandler)1