gpt4 book ai didi

java - 尝试写入对象时获取 NotSerializableException

转载 作者:行者123 更新时间:2023-12-03 19:10:19 26 4
gpt4 key购买 nike

尝试序列化 Lot 对象并将其发送到套接字。获取错误:

java.io.NotSerializableException: com.server.ClientServiceThread

为什么?

public class ClientServiceThread extends Thread  {... // form here called sendObj ...}

public class FlattenLot {
public void sendObj(){
try {
out = new ObjectOutputStream(oStream);
out.writeObject(lot); // error
out.flush();
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}

地段等级:

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import java.util.Date;
import java.util.Calendar;

public class Lot implements Serializable{
private static final long serialVersionUID = 1L;
public ArrayList<ClientServiceThread> clientBidsLog = new ArrayList<ClientServiceThread>();
public ArrayList<Integer> bidLog = new ArrayList<Integer>();

private List<Integer> bids = new ArrayList<Integer>();
private List<ClientServiceThread> clients = new ArrayList<ClientServiceThread>();

private String NAME;
private int INITIAL_PRICE;

private int MAX_BID = 0;
public volatile boolean notAvailable = false;
Lot(String name, int initPrice){
NAME = name;
INITIAL_PRICE = initPrice;
}
public synchronized String getName(){return NAME;}
public synchronized int getInitPrice(){return INITIAL_PRICE;}
public synchronized void subscribe(ClientServiceThread t){
clients.add(t);
}
public synchronized void unsubscribe(ClientServiceThread t){
clients.remove(t);
}
public synchronized boolean makeBid(ClientServiceThread t,int i){
if(i > INITIAL_PRICE && i > MAX_BID){
clientBidsLog.add(t);
bidLog.add(i);
bids.add(i);
MAX_BID = i;
t.LAST_BID = i;
notifyAllSubscribers("New bid: "+this.getMaxBid()+" made by "+this.clientBidsLog.get(this.clientBidsLog.size()-1).CLIENT_NAME);
return true;
}else{
return false;
}


}
public synchronized void notifyAllSubscribers(String msg){
for (ClientServiceThread client : clients){
client.lotUpdated(this, msg);
}
}
public synchronized int getMaxBid(){return MAX_BID;}

private Date time;

public Lot() {
time = Calendar.getInstance().getTime();
}

public Date getTime() {
return time;
}
}

最佳答案

该错误是由于试图序列化一个不可序列化的 ClientServiceThread 引起的。其中一个是 Lot 的一部分。如果 Lot 未使用 ClientServiceThread 字段(或包含 ClientServiceThread 的字段)声明,则另一种可能性是 Lot 是具有此类字段的类的非静态内部类。外部类实例将成为 Lot 的(隐藏)成员。

解决方案是要么使 ClientServiceThread 可序列化(不太可能,从它的名字看),要么通过标记相关字段 transient (或者将它们从 Lot 类中移除)。

关于java - 尝试写入对象时获取 NotSerializableException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10907838/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com