gpt4 book ai didi

java - NotSerializableException 对象IO

转载 作者:行者123 更新时间:2023-11-29 03:56:12 25 4
gpt4 key购买 nike

我正在尝试使用对象输出流将我制作的对象写入文件,每当我运行代码时,它都会抛出 NotSerializableException。如果您看到我做错了什么,请告诉我。

保存方法:

public static void saveEntity(PhysicsBody b, File f) throws IOException {
if (!f.exists())
f.createNewFile();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
oos.writeObject(b);
oos.close();
}

错误输出:

java.io.NotSerializableException: PhysicsBody
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at PhysicsUtil.saveEntity(PhysicsUtil.java:15)
at applet.run(applet.java:51)
at java.lang.Thread.run(Unknown Source)

PhysicsBody 类:

import java.awt.geom.Point2D;
import java.util.ArrayList;

public class PhysicsBody {

protected float centerX;
protected float centerY;
protected float minX, minY, maxX, maxY;
protected float mass;
protected ArrayList<Vertex> vertices = new ArrayList<Vertex>();
protected ArrayList<Edge> edges = new ArrayList<Edge>();

public PhysicsBody(float mass) {
this.mass = mass;
}

public void addVertex(Vertex v) {
if (v != null)
vertices.add(v);
}

public void addEdge(Edge e) {
if (e != null)
edges.add(e);
}

public MinMax projectToAxis(Point2D.Float axis) {
float dotP = axis.x * vertices.get(0).x + axis.y * vertices.get(0).y;
MinMax data = new MinMax(dotP, dotP);

for (int i = 0; i < vertices.size(); i++) {
dotP = axis.x * vertices.get(i).x + axis.y * vertices.get(i).y;
data.min = Math.min(data.min, dotP);
data.max = Math.max(data.max, dotP);
}
return data;
}

public void calculateCenter() {
centerX = centerY = 0;

minX = 10000.0f;
minY = 10000.0f;
maxX = -10000.0f;
maxY = -10000.0f;

for (int i = 0; i < vertices.size(); i++) {
centerX += vertices.get(i).x;
centerY += vertices.get(i).y;

minX = Math.min(minX, vertices.get(i).x);
minY = Math.min(minY, vertices.get(i).y);
maxX = Math.max(maxX, vertices.get(i).x);
maxY = Math.max(maxY, vertices.get(i).y);
}

centerX /= vertices.size();
centerY /= vertices.size();
}

}

最佳答案

PhysicsBody 必须实现 java.io.SerializableVertexEdge 也应该实现它。

关于java - NotSerializableException 对象IO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6286640/

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