com.buger.patcher.impl.StrategyBasedObjectPatcher Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of object-patcher Show documentation
Show all versions of object-patcher Show documentation
Java Object Patcher is simple,
dependency-free and fast library
which makes patching/merging objects simple.
The newest version!
package com.buger.patcher.impl;
import com.buger.patcher.ObjectPatcher;
import com.buger.patcher.Utils;
import com.buger.patcher.exception.PatchException;
import com.buger.patcher.resolver.FieldValueResolver;
import com.buger.patcher.strategy.FieldStrategyBasedFieldValueResolverFactory;
import java.lang.reflect.Field;
import java.util.Set;
/**
* @author Created by Buheria Oleksii {@literal [email protected]}
* @version 1.0
* @since 27-09-2020
*/
public class StrategyBasedObjectPatcher implements ObjectPatcher {
private final FieldStrategyBasedFieldValueResolverFactory factory;
public StrategyBasedObjectPatcher() {
this.factory = new FieldStrategyBasedFieldValueResolverFactory();
}
public T patch(S source, T target) throws PatchException {
try {
Set commonFields = Utils.getCommonFields(source.getClass(), target.getClass());
for (Field field : commonFields) {
FieldValueResolver fieldValueResolver = factory.createFieldPatcher(field);
if (fieldValueResolver != null) {
boolean wasAccessible = field.isAccessible();
if (!wasAccessible) {
field.setAccessible(true);
}
Object sourceFieldValue = fieldValueResolver.resolveFieldValue(source, target);
field.set(target, sourceFieldValue);
if (!wasAccessible) {
field.setAccessible(false);
}
}
}
return target;
} catch (Exception e) {
throw new PatchException("Cannot patch object or partially patched object", e);
}
}
}