Posted on 2009-07-02 09:24
morcble的blog 阅读(1149)
评论(0) 编辑 收藏 所属分类:
Java
public static synchronized void paseCode(Object obj,String fromEncode,String toEncode){
HashMap<String,Method> setMethodMap = new HashMap<String,Method>();
HashMap<String,Method> getMethodMap = new HashMap<String,Method>();
List<String> propertyList= new ArrayList<String>();
Method[] methods = obj.getClass().getDeclaredMethods();
for(Method method:methods){
String methodName = method.getName();
if( methodName.indexOf("get")!=-1){
if(method.getReturnType().equals(String.class)){
getMethodMap.put(methodName.substring(3),method);
propertyList.add(methodName.substring(3));
}
}
else if( methodName.indexOf("set")!=-1){
if(method.getParameterTypes()[0].equals(String.class)){
setMethodMap.put(methodName.substring(3),method);
}
}
}
String tempvalue = null;
String propertyName = null;
for(int i = 0;i <propertyList.size();i++){
try {
propertyName = propertyList.get(i);
tempvalue = (String) getMethodMap.get(propertyName).invoke(obj, new Object[0]);
if(tempvalue!=null&&!tempvalue.equals(""))
tempvalue = new String(tempvalue.getBytes(fromEncode),toEncode);
setMethodMap.get(propertyName).invoke(obj, tempvalue);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
test eg paseCode(new Object(),"GB2312","latin1")