Handwritten serialization and deserialization classes

This article further strengthens the understanding of reflection in java's advanced features by implementing a serialization and deserialization tool class.

achieve effect

Instantiate the Person class through the constructor. Deserialize and output text through the toString method of the PersonCast class; re-instantiate the Person object through the toObject method.

output result

Realize ideas

  • serialized object
    Ⅰ. Get the Class object of the object
    Ⅱ. Use the Class object to get the class name and field name of the object
    Ⅲ. Use Field object to get property value
    Ⅳ. Arrange the text format and output the text

  • deserialize object
    Ⅰ. Obtain the Class object of the deserialized object according to the text and initialize it
    Ⅱ. Use the Class object to instantiate objects
    Ⅲ. Parse the object attribute name and attribute content in the text, and use the Field object for assignment
    Ⅳ. Returning the object

implementation code

public class PersonCast {
    private Person person;

    public PersonCast(Person person) {
        this.person = person;

    public String toString() {
        StringBuilder personString = new StringBuilder();
        List<String> stringList = new ArrayList<>();
        Class<?> cls = this.person.getClass();

        //Get object class name
        //Get field property name
        Field[] fields = cls.getDeclaredFields();
        //Traverse to get the content of the field attribute
        for (Field f : fields) {
            try {
                String elm = f.getName() + "=" + f.get(this.person);
            } catch (IllegalAccessException e) {
        personString.append(String.join(",", stringList));
        return personString.toString();

    public Object toObject(String objectString) {
        //get class name
        String className = objectString.substring(0, objectString.indexOf("{"));
        //Get property name and content
        String[] fieldArr = objectString.substring(objectString.indexOf("{")+1, objectString.lastIndexOf("}")).split(",");

        try {
            //Initialize the object
            Class<?> cls = Class.forName(className);
            //instantiated object
            Object obj = cls.newInstance();//In fact, you can also use object properties to instantiate
            //Populate object properties
            for (String s : fieldArr) {
                String fieldContext[] = s.split("=");
                String fieldName = fieldContext[0];
                String fieldValue = fieldContext[1];
                Field field = cls.getDeclaredField(fieldName);
            return obj;
        } catch (ClassNotFoundException e) {
        } catch (IllegalAccessException e) {
        } catch (InstantiationException e) {
        } catch (NoSuchFieldException e) {
        return null;

    private void setFieldValue(Field field, Object obj, String value) {
        Class<?> type = field.getType();
        try {
            if (type == int.class) {
                field.setInt(obj, Integer.parseInt(value));
            } else if (type == byte.class) {
                field.setByte(obj, Byte.parseByte(value));
            } else if (type == short.class) {
                field.setShort(obj, Short.parseShort(value));
            } else if (type == long.class) {
                field.setLong(obj, Long.parseLong(value));
            } else if (type == float.class) {
                field.setFloat(obj, Float.parseFloat(value));
            } else if (type == double.class) {
                field.setDouble(obj, Double.parseDouble(value));
            } else if (type == char.class) {
                field.setChar(obj, value.charAt(0));
            } else if (type == boolean.class) {
                field.setBoolean(obj, Boolean.parseBoolean(value));
            } else if (type == String.class) {
                field.set(obj, value);
            } else {
                //Suppose there is a constructor of type String
                Constructor<?> ctor = type.getConstructor(
                        new Class[]{String.class});
                field.set(obj, ctor.newInstance(value));
        } catch (Exception e) {

public class Person {
    private String name;
    private Integer age;
    private Double birth;

    public Person() {

    public Person(String name, Integer age, Double birth) {
        this.name = name;
        this.age = age;
        this.birth = birth;

    public String getName() {
        return name;

    public void setName(String name) {
        this.name = name;

    public Integer getAge() {
        return age;

    public void setAge(Integer age) {
        this.age = age;

    public Double getBirth() {
        return birth;

    public void setBirth(Double birth) {
        this.birth = birth;

    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", birth=" + birth +

In reflection, the entry is the Class class. There are three ways to get the Class class object

  • Use classname.class directly
  • Use instance object.getClass()
  • class.forName( class name)

Then, according to the Class, obtain attribute objects such as field,method,consrtuctor, etc., initialize the object, access and modify members, modify methods, etc.


In the end, I suddenly thought that springmvc has a similar application scenario. The Dto object directly returned in the Controller class is output in the form of json in the interface, which is the process of serializing object properties;
When using the form form to submit json data, springmvc parses the json into objects, which is the process of deserialization.

Tags: Java

Posted by buildakicker on Sun, 15 May 2022 13:07:47 +0300