객체 전환 맵 도구 클래스 BeanUtil

6427 단어 util
1、
2. isAccessible () 의 결과가false일 때 반사로private 변수에 접근할 수 없습니다.
package com.yung.ppapi.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanMap;
import org.springframework.beans.BeanUtils;

import com.yung.ppapi.integration.dto.YCPFExpressDTO;

/**
 * 
 * @author lisheng4
 *
 */
public class BeanUtil {
	
    public static  T clone(Object source, Class type) {
        try {
        	if (source == null) {
        		return null;
        	}
            T target = type.newInstance();
            BeanUtils.copyProperties(source, target);
            return target;
        } catch (Exception e) {
        	e.printStackTrace();
            return null;
        } 
    } 
    public static  T clone(Object source, Class type, String... ignoreProperties) {
        try {
        	if (source == null) {
        		return null;
        	}
            T target = type.newInstance();
            BeanUtils.copyProperties(source, target, ignoreProperties);
            return target;
        } catch (Exception e) {
        	e.printStackTrace();
            return null;
        } 
    } 
	
	/**
	 *  
	 * @param map
	 * @param beanClass
	 * @return
	 * @throws Exception
	 */
	public static Object mapToObject(Map map, Class> beanClass) throws Exception {
		if (map == null) {
			return null;
		}

		Object obj = beanClass.newInstance();

		Field[] fields = obj.getClass().getDeclaredFields();
		for (Field field : fields) {
			int mod = field.getModifiers();
			if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
				continue;
			}
			
			boolean accessFlag = field.isAccessible();
			field.setAccessible(true);//  
			field.set(obj, map.get(field.getName()));
			field.setAccessible(accessFlag);
		}

		return obj;
	}
	
	/**
	 *  
	 * 
  • *
  • 10 * @param obj * @return * @throws Exception */ public static Map objectToMap(Object obj) throws Exception { if (obj == null) { return null; } Map map = new HashMap(); Field[] fields = obj.getClass().getDeclaredFields(); for (int i = 0, len = fields.length; i < len; i++) { String varName = fields[i].getName(); boolean accessFlag = fields[i].isAccessible(); fields[i].setAccessible(true);// Object valueObj = fields[i].get(obj); if (valueObj != null) { map.put(varName, valueObj); } fields[i].setAccessible(accessFlag); } return map; } /** * java.beans.Introspector * @param map * @param beanClass * @return * @throws Exception */ public static Object mapToObject2(Map map, Class> beanClass) throws Exception { if (map == null) return null; Object obj = beanClass.newInstance(); BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { Method setter = property.getWriteMethod(); if (setter != null) { setter.invoke(obj, map.get(property.getName())); } } return obj; } /** * java.beans.Introspector * @param obj * @return * @throws Exception */ public static Map objectToMap2(Object obj) throws Exception { if(obj == null) return null; Map map = new HashMap(); BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); if (key.compareToIgnoreCase("class") == 0) { continue; } Method getter = property.getReadMethod(); Object value = getter!=null ? getter.invoke(obj) : null; map.put(key, value); } return map; } /** * org.apache.commons.beanutils.BeanUtils * @param map * @param beanClass * @return * @throws Exception */ public static Object mapToObject3(Map map, Class> beanClass) throws Exception { if (map == null) return null; Object obj = beanClass.newInstance(); org.apache.commons.beanutils.BeanUtils.populate(obj, map); return obj; } /** * org.apache.commons.beanutils.BeanMap * @param obj * @return */ public static Map,?> objectToMap3(Object obj) { if(obj == null) return null; return new BeanMap(obj); } // public static void main(String[] args) throws Exception { // List> mapList = new ArrayList>(); // List> mapList2 = new ArrayList>(); // List> mapList3 = new ArrayList>(); // long t11 = System.currentTimeMillis(); // for(int i=1;i<=100000;i++) { // mapList.add(objectToMap(new YCPFExpressDTO())); // } // long t12 = System.currentTimeMillis(); // // long t21 = System.currentTimeMillis(); // for(int i=1;i<10000;i++) { // mapList2.add((Map) objectToMap2(new YCPFExpressDTO())); // } // long t22 = System.currentTimeMillis(); // // long t31 = System.currentTimeMillis(); // for(int i=1;i<10000;i++) { // mapList3.add((Map) objectToMap3(new YCPFExpressDTO())); // } // long t32 = System.currentTimeMillis(); // System.out.println(t12-t11); // System.out.println(t22-t21); // System.out.println(t32-t31); // //System.out.println(t32-t31); // } }

  •  
     
    참고 자료:https://www.cnblogs.com/XuYiHe/p/6871799.html
    참고 자료:https://blog.csdn.net/o_nianchenzi_o/article/details/78022416
     
     
    "건물주가 이렇게 고생하니, 건물주의 추천 코드를 사용하여 알리페이 훙바오를 받으세요, 꼭 소비하세요."윈윈^ ^.
    1. 알리페이의 첫 페이지를 열고'8282987'을 검색하면 바로 보너스를 받습니다.

    좋은 웹페이지 즐겨찾기