通过套接字接收序列化对象时出现 ClassNotFoundException
Posted
技术标签:
【中文标题】通过套接字接收序列化对象时出现 ClassNotFoundException【英文标题】:Getting ClassNotFoundException when receiving serialized object over socket 【发布时间】:2014-01-07 13:31:53 【问题描述】:首先,我使用的对象(书)应该没问题:
public class Book implements Serializable
private static final long serialVersionUID = 1L;
private String name;
private String publisher;
private int numbOfPages;
private int id;
而且服务端和客户端都有(复制粘贴,没有修改)。所以肯定不是这样的。
服务器:
ArrayList<Book> library = this.sql_db.getAllBooks();
try
ObjectOutputStream objOut = new ObjectOutputStream(
this.client.getOutputStream());
objOut.writeObject(library);
objOut.flush();
客户:
ArrayList<Book> library = new ArrayList<Book>();
try
ObjectInputStream objIn = new ObjectInputStream(Client.socket.getInputStream());
//library = (ArrayList<Book>) objIn.readObject(); // This is where the stack trace is pointing to
Object o = objIn.readObject(); // well actually here, since I commented last line and added this.
同样,book 在两个程序中都是相同的,并且在同一个包中。
堆栈跟踪指向我的注释文本,但以防万一,这里是:
java.lang.ClassNotFoundException: db.Book
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at java.io.ObjectInputStream.resolveClass(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at java.util.ArrayList.readObject(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at client.Client.requestAllBooks(Client.java:39)
at handler.HandleUserRequest.<init>(HandleUserRequest.java:19)
at run.Main.main(Main.java:8)
【问题讨论】:
Client
类中第 39 行的内容
就像我说的,我的评论行。对象o(在此之前,数组列表'library')
您的客户类路径中的db.Book.class
也是?
【参考方案1】:
该类必须存在于接收方的 CLASSPATH 中。序列化不适合你。
【讨论】:
以上是关于通过套接字接收序列化对象时出现 ClassNotFoundException的主要内容,如果未能解决你的问题,请参考以下文章
在 Iphone SDK 上接收带有异步 Udp 套接字的 UPS 包时出现问题
通过蓝牙发送序列化对象时出现 StreamCorruptedException
通过 Android 中的 Intent 反序列化 Serializable 对象时出现 ClassNotFoundException