jFinal Record 与 Mode 互转



import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.Map;
import org.apache.commons.beanutils.ConvertUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;



public class RecordUtils {
	
	
	private static final Logger logger = LoggerFactory.getLogger(RecordUtils.class);

	/**
	 * Model 转 Record
	 * @param bean
	 * @return
	 */
	public static  Record converRecord(Model<?> model) { 
	       Record      r =new Record(); 
	       r.setColumns(model); 
	       return r;
	}
	
	
	/**
	 * Record 转 任意实例类
	 * @param type
	 * @param record
	 * @return
	 */
	public static <T> T converModel(Class<T> clazz,Record record){
		
		try {
			return	  convertMap(clazz, record.getColumns());
		} catch (Exception e) { 
			logger.error("Record 转 T 异常... ",e);
		} 
		
	 return null;
	}
	
	
	public static <T> T convertMap(Class<T> type, Map<String, Object> map) throws Exception {
		T  obj = type.newInstance();
		
		// 获取类属性
		BeanInfo beanInfo = Introspector.getBeanInfo(type);

		// 给 JavaBean 对象的属性赋值
		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
		for (int i = 0; i < propertyDescriptors.length; i++) {
			PropertyDescriptor descriptor = propertyDescriptors[i];
			String propertyName = descriptor.getName();

			if (map.containsKey(propertyName)) {
				String value = ConvertUtils.convert(map.get(propertyName));
				Object[] args = new Object[1];
				args[0] = ConvertUtils.convert(value, descriptor.getPropertyType());

				descriptor.getWriteMethod().invoke(obj, args);

			}
		}
		return obj;
	}
	
 public static void main(String[] args) {
	 	//Model 
		Friend friend = new Friend();
		friend.setID(111L);
		friend.setIMAGES("image");
		friend.setMSG("msgsss");
		 
		
		 Record r  = 	converRecord(friend);
		 System.out.println(r.getStr("IMAGES"));
		 
		 Friend friendsss =converModel(Friend.class, r);
	     System.out.println(friendsss.getID());
	}
	 

随便发发 ^^

转载于:https://my.oschina.net/u/2450343/blog/859638

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值