All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.polaris.core.converter.BeanConverter Maven / Gradle / Ivy

There is a newer version: 3.2.1
Show newest version
package io.polaris.core.converter;

import io.polaris.core.io.Serializations;
import io.polaris.core.json.JsonSerializer;
import io.polaris.core.lang.JavaType;
import io.polaris.core.lang.bean.Beans;
import io.polaris.core.lang.copier.Copiers;
import io.polaris.core.lang.copier.CopyOptions;
import io.polaris.core.reflect.Reflects;
import io.polaris.core.service.StatefulServiceLoader;

import java.lang.reflect.Type;
import java.util.Map;
import java.util.Optional;

/**
 * @author Qt
 * @since 1.8
 */
public class BeanConverter extends AbstractConverter {
	private final JavaType targetType;
	private final CopyOptions copyOptions;

	public BeanConverter(Type beanType) {
		this(beanType, CopyOptions.create().ignoreError(true));
	}

	public BeanConverter(Type beanType, CopyOptions copyOptions) {
		this(JavaType.of(beanType), copyOptions);
	}

	public BeanConverter(JavaType beanType, CopyOptions copyOptions) {
		this.targetType = beanType;
		this.copyOptions = copyOptions.converter((t, s) -> Converters.convert(t, s));
	}

	@Override
	public JavaType getTargetType() {
		return this.targetType;
	}

	@Override
	protected  T doConvert(S value, JavaType targetType, JavaType sourceType) {
		if (sourceType.getRawType() instanceof Class) {
			if (targetType.getRawClass().isAssignableFrom((Class) sourceType.getRawType())){
				return (T) value;
			}
		} else if (targetType.getRawType() == sourceType.getRawType()) {
			return (T) value;
		}

		if (value instanceof Map || Beans.isBeanClass(value.getClass())) {
			T target = Reflects.newInstanceIfPossible(targetType.getRawClass());
			return Copiers.copy(value, target, targetType.getRawType(), copyOptions);
		}
		if (value instanceof byte[]) {
			return (T) Serializations.deserialize((byte[]) value);
		}

		if (value instanceof CharSequence) {
			// 扩展json实现,
			Optional optional = StatefulServiceLoader.load(JsonSerializer.class).optionalService();
			if (optional.isPresent()) {
				String json = value.toString();
				return optional.get().deserialize(json, targetType.getRawType());
			}
		}

		throw new UnsupportedOperationException();
	}
}