Trying to copy a source object which has ENUM property "valuetype"into destination object where "valuetype" is an integer. But seems like it doesn't work.
Source
import com.ns.enums.DataType;
import lombok.Getter;
@Getter
public class UpdateConfigRequest {
private String isenabled;
private String value;
private DataType valuetype;
}
Target
import org.joda.time.DateTime;
import org.springframework.data.annotation.Id;
import org.springframework.data.cassandra.mapping.PrimaryKey;
import org.springframework.data.cassandra.mapping.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Table("config")
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Config {
@PrimaryKey
@Id
private String key;
private DateTime created;
private DateTime lastmodified;
private boolean isenabled;
private String value;
private Integer valuetype;
}
*Bean Merge Class
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.beanutils.PropertyUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.PropertyAccessorFactory;
public class BeanMerger {
private static String[] getNullPropertyNames(Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<String>();
for (java.beans.PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null)
emptyNames.add(pd.getName());
}
String[] result = new String[emptyNames.size()];
System.out.println(result.length);
return emptyNames.toArray(result);
}
public static Object merge(Object source, Object target) {
BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
if (propertyExists(source, "lastmodified")) {
BeanWrapper trgWrap = PropertyAccessorFactory.forBeanPropertyAccess(source);
trgWrap.setPropertyValue("lastmodified", new DateTime());
}
return source;
}
private static boolean propertyExists(Object bean, String property) {
return PropertyUtils.isReadable(bean, property) && PropertyUtils.isWriteable(bean, property);
}
}
As attached above Im trying to merge UpdateConfigRequest class to Config using the BeanMerge.merge() wrapper written on top of Spring bean utils. I see everything thing works fine, except the copy of enum value. I suspect change in the datatype from enum to int is causing the issue. Anyways to overcome this ?
Aucun commentaire:
Enregistrer un commentaire