这篇文章将为大家详细讲解有关利用Java怎么对对象进行操作,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
对象复制(反射法)
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();
}
}
}
对象复制(fastJson转换)
单个
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实现,属性不一样必须用注解
对象转MAP
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;
}
关于利用Java怎么对对象进行操作就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。