Search in sources :

Example 1 with MergeProperty

use of com.baidu.hugegraph.annotation.MergeProperty in project incubator-hugegraph-toolchain by apache.

the class EntityUtil method merge.

@SuppressWarnings("unchecked")
public static <T extends Mergeable> T merge(T oldEntity, T newEntity) {
    Class<?> clazz = oldEntity.getClass();
    T entity;
    try {
        entity = (T) clazz.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        throw new InternalException("reflect.new-instance.failed", e, clazz.getName());
    }
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        // NOTE: Skip jacoco injected field
        if (field.getName().startsWith("$")) {
            continue;
        }
        MergeProperty property = field.getAnnotation(MergeProperty.class);
        if (property == null) {
            continue;
        }
        field.setAccessible(true);
        try {
            Object oldFieldValue = field.get(oldEntity);
            Object newFieldValue = field.get(newEntity);
            if (property.useNew()) {
                if (property.ignoreNull() && newFieldValue == null) {
                    field.set(entity, oldFieldValue);
                } else {
                    field.set(entity, newFieldValue);
                }
            } else {
                field.set(entity, oldFieldValue);
            }
        } catch (IllegalAccessException e) {
            throw new InternalException("reflect.access-field.failed", e, field.getName(), clazz.getName());
        }
    }
    return entity;
}
Also used : Field(java.lang.reflect.Field) MergeProperty(com.baidu.hugegraph.annotation.MergeProperty) InternalException(com.baidu.hugegraph.exception.InternalException)

Aggregations

MergeProperty (com.baidu.hugegraph.annotation.MergeProperty)1 InternalException (com.baidu.hugegraph.exception.InternalException)1 Field (java.lang.reflect.Field)1