我在很长一段时间内收到NotSerializableException。 完整的错误是这样的
java.io.NotSerializableException: sun.java2d.SunGraphics2D
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at SOM_thread1.run(soms1.java:354)
错误在out.writeObject(g)上; 完整代码如下
public class soms1 extends JApplet implements Serializable {
/**
*
*/
private static final long serialVersionUID = -743443566771258883L;
// class of weights and samples which performs operations on the SOM
public static Screen screen = new Screen();
// Socket Connection
private static Socket clientSocket = null;
private static PrintStream os = null;
private static BufferedReader inputLine = null;
// thread responsible for updating Screen
static public SOM_thread1 thread = null;
Toolkit tool;
public void init() {
String sentence;
tool = Toolkit.getDefaultToolkit();
try {
clientSocket = new Socket("localhost", 6789);
thread = new SOM_thread1(clientSocket);
setup_applet();
setup_radios();
setup_layout();
screen.init_Screen();
thread.init();
thread.start();
inputLine = new BufferedReader(new InputStreamReader(System.in));
sentence = inputLine.readLine();
if (clientSocket != null && os != null
&& sentence.equals("server:apl")) {
thread.set_state(2);
}
} catch (UnknownHostException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
}
}
class SOM_thread1 extends Thread implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
int state = -1;
int MAX_ITER = 0;
float t;
float T_INC;
private ObjectOutputStream out = null;
private Socket clientSocket = null;
public transient Graphics g = null;
public SOM_thread1(Socket clientSocket) {
this.clientSocket = clientSocket;
}
/*Updates the class Screen according the to values retrieved from the user interface*/
public void run() {
while (true) {
// Send data to server
try {
g = soms1.screen.getGraphics();
out = new ObjectOutputStream(clientSocket.getOutputStream());
out.writeObject(g);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
// Allow other operations
yield();
} // while(true)
}
}
请通知我应该序列化哪个对象 提前谢谢
答案 0 :(得分:0)
您无法(有用)序列化Thread
子类。 Thread
超类包含本身不可序列化的状态。
实际的异常正在发生,因为这一行:
out.writeObject(g);
明确尝试序列化sun.java2d.SunGraphics2D
实例。它不可序列化。您可以做的最好的事情是尝试在反序列化的上下文中创建一个新的Graphics
对象。
FWIW,你的代码有很多对我来说没什么意义。序列化Graphics
对象有什么意义?你究竟想要实现什么目标?
我正在尝试通过图形对象将图形数据发送到服务器。因为我使用了sun.java2d.SunGraphics2D提供的Screen.getGraphics()方法。 screen只是一种生成图形地图的显示方法。
基本上,你要做的事情是不可能的。无法通过图形API以允许您在新设备上重建它的形式检索Graphics对象的状态(即屏幕上显示的内容)。
您应该以原始形式序列化您在设备上呈现的源数据,并在对其进行反序列化后重新呈现它。
答案 1 :(得分:0)
好吧,你正在编写g
方法返回的对象Screen.getGraphics()
,我假设(来自堆栈跟踪)返回类sun.java2d.SunGraphics2D
的实例。
如果你看一下它的签名
public final class SunGraphics2D extends java.awt.Graphics2D implements sun.awt.ConstrainableGraphics, java.lang.Cloneable, sun.java2d.DestSurfaceProvider {
你会发现它没有实现Serializable
而且它是final
,所以看起来你运气不好......