我目前正在使用jedis数据库库和HashMap。
我需要一个从HashMap反序列化类的方法。目标类不会使用除String和基本数据类型之外的任何数据类型。
这就是我目前所得到的:
public static <T> void Deserialize(T obj,final Map<String,String> map) throws IllegalArgumentException, IllegalAccessException {
Class objClass = obj.getClass();
Field[] fields = objClass.getDeclaredFields();
for(int i = 0; i < fields.length; i++) {
fields[i].setAccessible(true);
if(fields[i].getType() == String.class) {
fields[i].set(obj, map.get(fields[i].getName()));
}
}
}
但是还有其他选择而不是使用巨大的if else吗?
答案 0 :(得分:0)
所以我能够找到上一个问题提供的解决方案: How to convert from String to a primitive type or standard java Wrapper types
被问到的人的答案有一个优雅的解决方案(@Luigi R. Viggiano)。
package data;
import java.beans.PropertyEditor;
import java.beans.PropertyEditorManager;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class Reflection {
/**
* @param obj
* @return
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static <T> Map<String,String> Serialize(final T obj) throws IllegalArgumentException, IllegalAccessException {
//Local Variables
boolean flag;
Field current;
Map<String,String> map = new HashMap<String,String>();
//Load required Data
Class<? extends Object> objClass = obj.getClass();
Field[] fields = objClass.getDeclaredFields();
//Go through each field
for(int i = 0; i < fields.length; i++) {
current = fields[i];
//Check flag
flag = current.isAccessible();
//Make it accessible
if(!flag) {
current.setAccessible(true);
}
//Put Member on Map
map.put(fields[i].getName(), fields[i].get((Object)obj).toString());
//Reset Flag if Setted
if(!flag) {
current.setAccessible(false);
}
}
return map;
}
/**
* @param obj
* @param map
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static <T> void Deserialize(final T obj,final Map<String,String> map) throws IllegalArgumentException, IllegalAccessException {
//Local Variables
boolean flag;
Field current;
//Load required Data
Class objClass = obj.getClass();
Field[] fields = objClass.getDeclaredFields();
//Go through each field
for(int i = 0; i < fields.length; i++) {
current = fields[i];
//Check flag
flag = current.isAccessible();
//Make it accessible
if(!flag) {
current.setAccessible(true);
}
//Set member from the map key and convert it into the desired type
current.set(obj, convert(current.getType(), map.get(current.getName())));
//Reset Flag if Setted
if(!flag) {
current.setAccessible(false);
}
}
}
/**
* @param targetType
* @param text
* @return
*/
private static Object convert(Class<?> targetType, String text) {
//Find Editor for desired Type
PropertyEditor editor = PropertyEditorManager.findEditor(targetType);
//Load String
editor.setAsText(text);
//Retrive converted Type as Object
return editor.getValue();
}
}
这是序列化和反序列化的最终解决方案。不知何故,ProperyManager在Android上无法实现,因此无法在Android上运行。