package com.apobates.forum.utils.lang;

import com.apobates.forum.utils.Commons;
import java.lang.reflect.InvocationTargetException;
import java.util.Objects;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author xiaofanku
 * @param <T>
 * @param <D>
 */
public interface ForumReplicable<T,D extends T> {
    final static Logger logger = LoggerFactory.getLogger(ForumReplicable.class);
    
    /**
     * 基于ForumReplicable接口的静态副本,要求T,D的无参构造器是公共且开放的
     * @param <T>
     * @param <D>
     * @param entity
     * @param srcClass
     * @return 
     */
    static <T,D> Optional<D> replica(T entity, Class<D> srcClass){
        Objects.requireNonNull(entity);
        try {
            D destIns = srcClass.getDeclaredConstructor().newInstance();
            Commons.copyProperties(destIns, entity);
            return Optional.ofNullable(destIns);
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException ex) {
            if(logger.isDebugEnabled()){
                logger.debug("静态副本构造过程出现异常", ex);
            }
        }
        return Optional.empty();
    }
}