java.io.InvalidClassException: Person; no valid constructor
at java.io.ObjectStreamClass$ExceptionInfo.newInvalidClassException(Obje
ctStreamClass.java:147)
at java.io.ObjectStreamClass.checkDeserialize(ObjectStreamClass.java:755
)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1
751)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1347)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at ReadObject.main(ReadObject.java:23)
public void setAge(int age) { this.age = age; } public int getAge() { return this.age; } public void writeExternal(java.io.ObjectOutput out) throws IOException { // 将name Field的值反转后写入二进制流 out.writeObject(new StringBuffer(name).reverse()); out.writeInt(age); } public void readExternal(java.io.ObjectInput in) throws IOException, ClassNotFoundException { // 将读取的字符串反转后赋给name Field this.name = ((StringBuffer)in.readObject()).reverse().toString(); this.age = in.readInt(); } }
import java.io.*; /** * Description: * <br/>网站: <a * <br/>Copyright (C), 2001-2012, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class WriteObject { public static void main(String[] args) { try( // 创建一个ObjectOutputStream输出流 ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream("object.txt"))) { Person per = new Person("孙悟空", 500); // 将per对象写入输出流 oos.writeObject(per); } catch (IOException ex) { ex.printStackTrace(); } } }
import java.io.*; /** * Description: * <br/>网站: <a * <br/>Copyright (C), 2001-2012, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class ReadObject { public static void main(String[] args) { try( // 创建一个ObjectInputStream输入流 ObjectInputStream ois = new ObjectInputStream( new FileInputStream("object.txt"))) { // 从输入流中读取一个Java对象,并将其强制类型转换为Person类 Person p = (Person)ois.readObject(); System.out.println("名字为:" + p.getName() + "\n年龄为:" + p.getAge()); } catch (Exception ex) { ex.printStackTrace(); } } }
序列化没问题,反序列化报错,求解谢谢!
Person提供一个无参数的默认构造函数
你readExternal执行的前提是对象本身要存在,比如要提供默认构造函数给系统让他给你创建对象。
Person提供一个无参数的默认构造函数
你readExternal执行的前提是对象本身要存在,比如要提供默认构造函数给系统让他给你创建对象。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。