use of io.micronaut.serde.support.serializers.ObjectSerializer in project micronaut-serialization by micronaut-projects.
the class DefaultSerdeRegistry method findSerializer.
@Override
public <T> Serializer<? super T> findSerializer(Argument<? extends T> type) throws SerdeException {
Objects.requireNonNull(type, "Type cannot be null");
final TypeKey key = new TypeKey(type);
final Serializer<?> serializer = serializerMap.get(key);
if (serializer != null) {
// noinspection unchecked
return (Serializer<? super T>) serializer;
} else {
List<BeanDefinition<Serializer>> possibles = serializerDefMap.get(type.getType());
if (possibles == null) {
for (Map.Entry<Class<?>, List<BeanDefinition<Serializer>>> entry : serializerDefMap.entrySet()) {
final Class<?> targetType = entry.getKey();
if (targetType.isAssignableFrom(type.getType())) {
possibles = entry.getValue();
final Argument<?>[] params = type.getTypeParameters();
if (ArrayUtils.isNotEmpty(params)) {
// narrow for generics
possibles = new ArrayList<>(possibles);
final Iterator<BeanDefinition<Serializer>> i = possibles.iterator();
while (i.hasNext()) {
final BeanDefinition<Serializer> bd = i.next();
final Argument<?>[] candidateParams = bd.getTypeArguments(Serializer.class).get(0).getTypeParameters();
if (candidateParams.length == params.length) {
for (int j = 0; j < params.length; j++) {
Argument<?> param = params[j];
final Argument<?> candidateParam = candidateParams[j];
if (!((param.getType() == candidateParam.getType()) || (candidateParam.isTypeVariable() && candidateParam.getType().isAssignableFrom(param.getType())))) {
i.remove();
}
}
} else {
i.remove();
}
}
}
break;
}
}
}
if (possibles != null) {
if (possibles.size() == 1) {
final BeanDefinition<Serializer> definition = possibles.iterator().next();
final Serializer locatedSerializer = beanContext.getBean(definition);
serializerMap.put(key, locatedSerializer);
return locatedSerializer;
} else if (possibles.isEmpty()) {
throw new SerdeException("No serializers found for type: " + type);
} else {
final BeanDefinition<Serializer> definition = lastChanceResolve(type, possibles);
final Serializer locatedSerializer = beanContext.getBean(definition);
serializerMap.put(key, locatedSerializer);
return locatedSerializer;
}
} else {
serializerMap.put(key, objectSerializer);
}
}
return objectSerializer;
}
Aggregations