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

io.github.linpeilie.CycleAvoidingMappingContext Maven / Gradle / Ivy

There is a newer version: 1.4.4
Show newest version
package io.github.linpeilie;

import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
import org.mapstruct.BeforeMapping;
import org.mapstruct.MappingTarget;
import org.mapstruct.TargetType;

public class CycleAvoidingMappingContext {

    private Map, Object>> knownInstances = new IdentityHashMap<>();

    @BeforeMapping
    public  T getMappedInstance(Object source, @TargetType Class targetType) {
        Map, Object> map = knownInstances.get(source);
        if (map == null || map.isEmpty()) {
            return null;
        }
        return (T) map.get(targetType);
    }

    @BeforeMapping
    public void storeMappedInstance(Object source, @MappingTarget Object target) {
        if (target == null) {
            return;
        }
        Map, Object> map = knownInstances.get(source);
        if (map == null) {
            map = new HashMap<>();
        }
        map.put(target.getClass(), target);
        knownInstances.put( source, map );
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy