JAVA反射——java技术栈系列文章

IT黑名单 2017-5-15 14:00:26

目录

需求如下,有不同类型的两个对象:

Type1 bean1 = {'name':'test1','type1':'type1'};
Type2 bean2 = {'name':'','type2':''};
bean2 = copy(bean1);
bean2 = {'name':'test1','type2':''};

利用Java反射原理,实现如下:

import java.lang.reflect.Field;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Mapper {
	private static Logger log = LoggerFactory.getLogger(Mapper.class);
	public static <T> T map(Object source, Class<T> destinationClass) {
		if (null == source) {
			return null;
		}

		Map<String, Object> sourceMap = buildMap(source);
		return build(sourceMap, destinationClass);
	}
	
	private static Map<String, Object> buildMap(Object obj) {
		Map<String, Object> map = new HashMap<String, Object>();
		Field[] fields = obj.getClass().getDeclaredFields();

		try {
			for (Field field : fields) {
				field.setAccessible(true);
				map.put(field.getName(), field.get(obj));
			}
		} catch (IllegalArgumentException e) {
			log.error("class {} Access Illegal Argument.", obj.getClass());
		} catch (IllegalAccessException e) {
			log.error("class {} Access Illegal.", obj.getClass());
		}
		return map;
	}
	
	private static <T> T build(Map<String, Object> source, Class<T> destinationClass) {
		try {
			T destination = destinationClass.newInstance();
			Field[] fields = destinationClass.getDeclaredFields();
			for (Field field : fields) {
				if (source.containsKey(field.getName())) {
					field.setAccessible(true);
					field.set(destination, source.get(field.getName()));
				}
			}
			return destination;
		} catch (InstantiationException e) {
			log.error("destinationClass {} Instantiation error.",
					destinationClass);
		} catch (IllegalAccessException e) {
			log.error("destinationClass {} Access Illegal.", destinationClass);
		}
		return null;
	}
}
注:以上代码需要Type2有无参构造函数,否则会抛出 java.lang.InstantiationException 错误。


转载请注明来源【IT黑名单

本文链接:http://blog.itblacklist.cn/20170515/8451.html

© Copyright 2016 IT黑名单 Inc.All Rights Reserved. 豫ICP备15018592号-2