/**
-
@Autor: lssffy
-
@Description: Objekt kopieren
-
@date: 29.05.2023 10:33
*/
@Slf4j
öffentliche Klasse BeanCopy {public static T copy(Object source, Class target) { if(target == null){ return null; } try { T t = target.newInstance(); return copy(source,t); }catch (Exception e){ log.error(“Failed to copy:{}” , e); throw new BusinessException(CommonErrors.COPY_OBJ_FAIL,e); } }
public static T copy(Object source, T target){ if(target == null || source == null){ return null; } BeanCopier copier = BeanCopier.create(source.getClass(), target.getClass(),true); copier.copy(source, target, new Converter() { @Override public Object convert(Object obj, Class cls, Object context) { if(obj == null){ return null; } /** * source is String,target ist Datum / else if((obj Instanz von String) && Date.class.isAssignableFrom(cls)){ return DateUtils.parseDate((String) obj); } / * * Quelle ist Datum, Ziel ist String /
else if((obj exampleof Date) && String.class.isAssignableFrom(cls)){ return DateFormatUtils.format((Date) obj); } /
*
* Quelle ist kein String, Ziel ist String
/
else if(!(obj exampleof String) && String.class.isAssignableFrom(cls)) { return String.valueOf(obj); } /
*
* verschiedene benutzerdefinierte Objekte, aber mit demselben Feldnamen
*/
else if(cls.toString().contains(“com.example”) && !cls.equals(obj.getClass())){ return copy( obj, cls); } return obj; } }); Rückkehrziel; }/**
- Wenn Quelle und Ziel das aufzulistende Element sind, beide Objekte jedoch nicht mit dem Typ identisch sind.
- @param Quelle
- @param Ziel
- @param Properties
*/
public static void copyProperties(Object source,Object target,String… Properties){ BeanUtils.copyProperties(source,target,properties); }
public static T copyProperties(Object source,Class cls,String… Properties){ T target; Versuchen Sie es mit { target = cls.newInstance(); } Catch (Exception e){ log.error(“Eigenschaften können nicht kopiert werden:{}”, e); throw new BusinessException(CommonErrors.INSTANCE_OBJ_FAIL,e); } Ziel zurückgeben; }
öffentliche statische Liste copyList(List<?> source, Class cls){ if(source == null){ return null; } return source.stream().map(s->copy(s,cls)).collect(Collectors.toList()); } }