diff --git a/ruoyi-common/ruoyi-common-core/src/main/java/com/ruoyi/common/core/utils/BaseConvert.java b/ruoyi-common/ruoyi-common-core/src/main/java/com/ruoyi/common/core/utils/BaseConvert.java new file mode 100644 index 0000000..2f21d4b --- /dev/null +++ b/ruoyi-common/ruoyi-common-core/src/main/java/com/ruoyi/common/core/utils/BaseConvert.java @@ -0,0 +1,56 @@ +package com.ruoyi.common.core.utils; + +import org.springframework.beans.BeanUtils; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * 通用转换器基类 + * + * @param Source类型 + * @param Target类型 + * @author ruoyi + */ +public abstract class BaseConvert { + + private final Class sourceClass; + private final Class targetClass; + + protected BaseConvert(Class sourceClass, Class targetClass) { + this.sourceClass = sourceClass; + this.targetClass = targetClass; + } + + protected T innerFrom(F source) { + if (source == null) return null; + try { + T target = targetClass.getDeclaredConstructor().newInstance(); + BeanUtils.copyProperties(source, target); + return target; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + protected F innerTo(T target) { + if (target == null) return null; + try { + F source = sourceClass.getDeclaredConstructor().newInstance(); + BeanUtils.copyProperties(target, source); + return source; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + protected List innerFromList(List sourceList) { + if (sourceList == null) return null; + return sourceList.stream().map(this::innerFrom).collect(Collectors.toList()); + } + + protected List innerToList(List targetList) { + if (targetList == null) return null; + return targetList.stream().map(this::innerTo).collect(Collectors.toList()); + } +} \ No newline at end of file