Java常用オブジェクト操作ツールコードの例
オブジェクトコピー(反射法)個のcopyは、価値のあるオブジェクト を有する。 copyを必要としない属性用filterProp は、全属性の名称タイプが同じでなければなりません。
オブジェクトコピー(fastJson変換)
単一
オブジェクトマップ
public static void copyProp(Object from, Object to, String... filterProp) {
HashSet<String> filterSet = new HashSet<String>(Arrays.asList(filterProp));
Class<?> fromc = from.getClass();
Class<?> toc = to.getClass();
List<Field> to_fields = new ArrayList<Field>() ;
while (toc != null) {
to_fields.addAll(Arrays.asList(toc.getDeclaredFields()));
toc = toc.getSuperclass();
}
for (Field to_field : to_fields) {
try{
if (filterSet.contains(to_field.getName())||"serialVersionUID".equals(to_field.getName())) {
continue;
}
Field from_field = null;
try{
from_field = fromc.getDeclaredField(to_field.getName());
}catch (Exception e){
continue;
}
from_field.setAccessible(true);
Object value = from_field.get(from);
if(value==null){
continue;
}
to_field.setAccessible(true);
to_field.set(to, value);
}catch (Exception e){
e.printStackTrace();
}
}
}
単一
public static <T> T bean2OtherBean(Object bean, Class<T> tClass){
return JSON.parseObject(JSON.toJSONString(bean),tClass);
}
リスト
public static <T> List<T> list2OtherList(List originList, Class<T> tClass){
List<T> list = new ArrayList<>();
if(!CollectionUtils.isEmpty(originList)){
for (Object obj : originList) {
T t = bean2OtherBean(obj,tClass);
list.add(t);
}
}
return list;
}
fastjsonを実現するには、属性が違っています。オブジェクトマップ
public static <K,V> Map<K,V> bean2map(Object obj) throws IllegalAccessException {
Map<String, Object> map = new HashMap<>();
Class<?> clazz = obj.getClass();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = field.get(obj);
map.put(fieldName, value);
}
return (Map<K, V>) map;
}
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。