日期:2014-05-17 浏览次数:20776 次
package com.ytbysj.util;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Map.Entry;
import com.ytbysj.beans.Student;
import com.ytbysj.exception.FooException;
/**
* Message Handler类
* @author haniyaseyo
*
*/
public class MessageHandler {
/**
* 将message转换成Map对象
* @param message like:key=value|key=value||||
* @return 通过message转换成的MAP key=value
*/
public static Map<String,String> messageHandler(String message){
//如果message=null则抛出异常
if(message == null) throw new FooException("MessageHandler messageHandler(String message) message=null");
//判断message的格式
if(message.indexOf("|") == -1) throw new FooException("MessageHandler messageHandler(String message) message do not contains \"|\"");
if(message.indexOf("=") == -1) throw new FooException("MessageHandler messageHandler(String message) message do not contains \"=\"");
//定义Map对象
Map<String, String> map = new HashMap<String, String>();
//定义StringTokenizer对象 并指定"|"为分隔符
StringTokenizer stken = new StringTokenizer(message, "|");
/*
* 循环StringTokenizer中的对象 并复制到Map中
*/
while (stken.hasMoreTokens()) {
String[] temp = stken.nextToken().split("=");
map.put(temp[0], temp[1]);
}
return map;
}
/**
* 根据给定的message和Class构造一个?对象
* @param message like:key=value|key=value||||||
* @param clazz ?的Class对象
* @return clazz.newInstance()
*/
public static Object getObject(String message, Class<?> clazz){
//获取Map
Map<String, String> map = messageHandler(message);
//判断Map是否为空
if(map.isEmpty()) throw new FooException("MessageHandler getObject(String message, Class<?> clazz) map is empty");
Object obj = null;
try {
obj = clazz.newInstance();
Iterator<Entry<String,String>> ite = map.entrySet().iterator();
while(ite.hasNext()){
Entry<String,String> entry = ite.next();
//取出每一个key value
String item_name = entry.getKey().trim();
String value = entry.getValue().trim();
//构造方法名
String methodName = "set" + String.valueOf(item_name.charAt(0)).toUpperCase() + item_name.substring(1);
//获取Field的类型
Class<?> type = clazz.getDeclaredField(item_name).get