简体   繁体   English

将字符串反序列化为字段类型Java

[英]Deserialize a String into a Field Type Java

I'm currently working with the jedis Database library and a HashMap. 我目前正在使用jedis数据库库和HashMap。

I'm in need for a method to deserialize a class from a HashMap. 我需要一个从HashMap反序列化类的方法。 The target class wont use any datatypes except String and the primitive datatypes. 目标类不会使用除String和基本数据类型之外的任何数据类型。

This is what I got currently: 这就是我目前所得到的:

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()));
        }
    }
}

But is there another option instead of using a huge if else? 但是,还有其他选择而不是使用巨大的其他选择吗?

So I was able to find a solution provided by this previous question: How to convert from String to a primitive type or standard java Wrapper types 所以我能够找到前一个问题提供的解决方案: 如何从String转换为原始类型或标准java Wrapper类型

The answer by the one who asked has an elegant solution(@Luigi R. Viggiano). 被问到的人的答案有一个优雅的解决方案(@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();
}
}

This is the final solution for Serialization and Deserialization. 这是序列化和反序列化的最终解决方案。 Somehow ProperyManager is not aviable on Android so this wont work on Android. 不知怎的,ProperyManager在Android上是不可行的,所以这不适用于Android。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法反序列化 `java.util.LinkedHashMap 类型的值<java.lang.string,java.lang.string> ` 来自 Array 或什么是我的字段的正确类型</java.lang.string,java.lang.string> - Cannot deserialize value of type `java.util.LinkedHashMap<java.lang.String,java.lang.String>` from Array or what would be a correct type of my field Java JSON当type为String或List时反序列化<String> - Java JSON Deserialize when type is String or List<String> Java JSON将属性名称作为字段名称反序列化String - Java JSON deserialize String with property names as field names 无法从 String 反序列化 java.time.LocalDateTime 类型的值 - Can not deserialize value of type java.time.LocalDateTime from String 无法从 String 反序列化 java.sql.Timestamp 类型的值 - Cannot deserialize value of type java.sql.Timestamp from String 无法从字符串反序列化类型为java.sql.Timestamp的值 - Cannot deserialize value of type `java.sql.Timestamp` from String 无法从String反序列化`java.util.Date`类型的值 - Cannot deserialize value of type `java.util.Date` from String 为什么 Jackson ObjectMapper 给我这个错误,将 JSON 字段转换为日期 object? 无法从字符串反序列化 java.util.Date 类型的值 - Why Jackson ObjectMapper give me this error converting JSON field into a Date object? Can not deserialize value of type java.util.Date from String 将文档类型反序列化为Java类 - Deserialize Document type to a Java Class 用字符串和值创建预定义类型的字段,java - Create field of predefined type with string and value, java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM