【反序列化】编写Java反序列化的函数实现

代码

类名:wj33333

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;

public class wj33333 implements Serializable {
    public int age;
    public String name;

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        Runtime.getRuntime().exec("calc");
        //Runtime.getRuntime().exec("whoami");
        // 默认的反序列化操作
        in.defaultReadObject();
    }
}

类名:wj

import java.io.*;

public class wj {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        wj33333 p=new wj33333();
        p.age=18;
        p.name="wj33";

        serialize(p,"wj33.bin");


        System.out.println("反序列化结果:" + deserialize("wj33.bin"));
    }

    public static void serialize(Object obj, String filePath) throws IOException {
        try (FileOutputStream fileOut = new FileOutputStream(filePath);
             ObjectOutputStream objectOut = new ObjectOutputStream(fileOut)) {
            objectOut.writeObject(obj);
        }
    }

    public static Object deserialize(String filePath) throws IOException, ClassNotFoundException {
        try (FileInputStream fileIn = new FileInputStream(filePath);
             ObjectInputStream objectIn = new ObjectInputStream(fileIn)) {
            return objectIn.readObject();
        }
    }
}

结果

查看序列化的字节流

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Fastjson是一个Java语言编写的高性能JSON处理库,可以实现JSON字符串与Java对象之间的相互转换。在Fastjson中,反序列化就是将JSON字符串转换为Java对象的过程。 要进行Fastjson的反序列化,首先需要将JSON字符串作为输入,然后使用Fastjson提供的API将其转换为Java对象。以下是一个简单的示例代码: ```java import com.alibaba.fastjson.JSON; public class FastjsonExample { public static void main(String[] args) { String jsonString = "{\"name\":\"Alice\",\"age\":25}"; // 将JSON字符串反序列化Java对象 Person person = JSON.parseObject(jsonString, Person.class); System.out.println(person.getName()); // 输出:Alice System.out.println(person.getAge()); // 输出:25 } } class Person { private String name; private int age; // 省略构造函数和其他方法 // Getter和Setter方法 } ``` 在上述示例中,首先定义了一个Person类,该类包含了name和age两个属性。然后,使用`JSON.parseObject`方法将JSON字符串`jsonString`反序列化为Person对象。 需要注意的是,Fastjson会根据属性名匹配JSON中的字段,并将对应字段的值赋给属性。因此,在进行反序列化时,要确保Java类的属性名与JSON中的字段名一致,或者使用`@JSONField`注解来指定字段名和属性名之间的映射关系。 以上就是使用Fastjson进行反序列化的基本步骤和示例代码。希望能对你有所帮助!如果有更多问题,请继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值