I am trying to take data from a GUI and also from arraylists in my model class and then want to put them into another arraylist. Everytime the code runs, it works fine but then when I close the application and the serializer code runs the IOException gets thrown.
The only thing I access from the model class is an arraylist but I am accessing this array list in other classes and I don't have a problem.
Orginally I had the arraylist that I am adding to in the model class, I assumed that was what was throwing the exception so I moved it to another class, however the exception is still being thrown.
I have tried the rest of the event handlers on the form but this is the only one that causes the exception.
Here is the code that is causing the exception to occur:
private void btnRequestAppointmentActionPerformed(java.awt.event.ActionEvent evt) {
ArrayList<IAccountStrategy> observers;
observers = model.getObservers();
IAccountStrategy xx;
xx = observers.get(accountIndex);
ArrayList<Appointments> appointment;
appointment = xx.getAppointments();
Appointments app = new Appointments();
setAppointmentDates(appointment, app);
setAppointmentPatient(appointment, app);
xx.getAppointments().add(app);
JOptionPane.showMessageDialog(null, "Appointment Requested. A Secretary will check the request shortly");
}
And the classes that it is calling:
public void setAppointmentDates(ArrayList<Appointments> appointment, Appointments app){
String doctorsName = null;
String sDate;
Date appointmentDate = null;
Date formattedDate = null;
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try{
doctorsName = cboDoctor.getSelectedItem().toString();
sDate = cboDate.getSelectedItem().toString();
appointmentDate = sdf.parse(sDate);
formattedDate = sdf.parse(sdf.format(appointmentDate));
}
catch(ParseException ex){
System.out.println("ParseException has been caught");
}
app.setAppointmentDate(appointmentDate);
app.setPreferredDoctor(doctorsName);
}
public void setAppointmentPatient(ArrayList<Appointments> appointment, Appointments app){
ArrayList<IAccountStrategy> observers;
observers = model.getObservers();
IAccountStrategy xx;
xx = observers.get(accountIndex);
app.setPatientID(xx.getAccountID());
app.setPatientName(xx.getFirstname() +" "+ xx.getLastname());
app.setPatientAge(xx.getAge());
app.setPatientSex(xx.getSex());
}
This is the code for my serialization, it works on all my other classes:
private void formWindowClosing(java.awt.event.WindowEvent evt) {
String filename = "accounts.txt";
try{
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);
out.writeObject(model);
out.close();
file.close();
}
catch(IOException ex){
System.out.println("IOException has been caught");
}
}
Here is the stack trace:
java.io.NotSerializableException: patientmanagementsystemv2.items.Appointments
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at java.util.ArrayList.writeObject(ArrayList.java:766)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1140)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at java.util.ArrayList.writeObject(ArrayList.java:766)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1140)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at patientmanagementsystemv2.gui.PatientHomePage.formWindowClosing(PatientHomePage.java:294)
at patientmanagementsystemv2.gui.PatientHomePage.access$000(PatientHomePage.java:28)
at patientmanagementsystemv2.gui.PatientHomePage$1.windowClosing(PatientHomePage.java:133)
at java.awt.Window.processWindowEvent(Window.java:2054)
at javax.swing.JFrame.processWindowEvent(JFrame.java:305)
at java.awt.Window.processEvent(Window.java:2013)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2297)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:84)
at java.awt.EventQueue$4.run(EventQueue.java:733)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:730)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
I'm trying to get this program completed for tonight but I've been trying to fix this for hours. Any help is apprieciated.
Stacktrace
Like #Stultuske mention in the comments, you can find the reason inside the stacktrace
Finding Strategy
Lookup the first entry with the naming of your package. In your case look for patientmanagementsystemv2.gui
java.io.NotSerializableException: patientmanagementsystemv2.items.Appointments
...
at patientmanagementsystemv2.gui.PatientHomePage.formWindowClosing(PatientHomePage.java:294)
at patientmanagementsystemv2.gui.PatientHomePage.access$000(PatientHomePage.java:28)
at patientmanagementsystemv2.gui.PatientHomePage$1.windowClosing(PatientHomePage.java:133)
...
At the top of your stacktrace you can see that you have a NotSerializableException at patientmanagementsystemv2.gui.PatientHomePage.formWindowClosing(PatientHomePage.java:294.
The Problem
java.io.NotSerializableException: patientmanagementsystemv2.items.Appointments
The reference type Appointments seems not to implement Serializable and the error raises because you try to serialize in the method formWindowClosing with out.writeObject(model) an instance of Appointments.
Modify Appointments
If you own the class just write
public class Appointments implements Serializable {
// ...
}
But you expected an IOException
With catch(IOException ex) you catch an IOException and all subclasses of it including NotSerializableException.
Related
I use Apache Kafka Streams the Processor API.
I create a remote object that extends the UnicastRemoteObject inside the StateStore of the Processor.
When the init(ProcessorContext) method of the Processor (which extends the AbstractProcessor) of my topology is called I put a ProcessorContext reference inside that remote Object.
public void init(ProcessorContext processorContext){
super.init(processorContext);
this.myStore = (MyCustomStore<String, String>)context().getStateStore("mystore");
this.myStore.getRemoteObject().setProcessorContext(processorContext);
}
If I access the ProcessorContext only remotely and use the forward method to send records to a sink processor it works fine. And if I access the ProcessorContext only locally to send records with forward it works fine, too.
If I access the ProcessorContext both locally and remotely to use forward I have NPE. I used a synchronized method in which foward is called because I thought that two different threads try to access ProcessorContext at the same time but the NPE insists.
It seems to me that somehow the same thread calls forward at the same time
both locally and remotely and that throws NPE.
The message is:
java.lang.NullPointerException
at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:114)
at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:90)
at StateMessageBean.sendMessage(StateMessageBean.java:109)
at StateMessageBean.subroundEnded(StateMessageBean.java:87)
at sun.reflect.GeneratedMethodAccessor26.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:361)
at sun.rmi.transport.Transport$1.run(Transport.java:200)
at sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:283)
at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:260)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:161)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:227)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:179)
at com.sun.proxy.$Proxy25.subroundEnded(Unknown Source)
at CoordinatorProcessor.collectIncreaseOfC(CoordinatorProcessor.java:332)
at CoordinatorProcessor.process(CoordinatorProcessor.java:119)
at CoordinatorProcessor.process(CoordinatorProcessor.java:25)
at org.apache.kafka.streams.processor.internals.ProcessorNode$1.run(ProcessorNode.java:50)
at org.apache.kafka.streams.processor.internals.ProcessorNode.runAndMeasureLatency(ProcessorNode.java:244)
at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:133)
at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:143)
at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:126)
at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:90)
at org.apache.kafka.streams.processor.internals.SourceNode.process(SourceNode.java:87)
at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:302)
at org.apache.kafka.streams.processor.internals.AssignedStreamsTasks.process(AssignedStreamsTasks.java:94)
at org.apache.kafka.streams.processor.internals.TaskManager.process(TaskManager.java:409)
at org.apache.kafka.streams.processor.internals.StreamThread.processAndMaybeCommit(StreamThread.java:964)
at org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:832)
at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:767)
at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:736)
The two methods that I call remotely and locally are:
//remote method
#Override
public void subroundEnded()
{
PhiMessage newPhiMessage = new PhiMessage();
newPhiMessage.setSiteId(this.siteId);
newPhiMessage.setCurrentRound(this.currentRound);
newPhiMessage.setCurrentSubround(this.currentSubround);
newPhiMessage.setPhi(this.phi);
byte[] byteNewPhiMessage = SerializationUtils.serialize(newPhiMessage);
this.processorContext.forward("PhiMessage", byteNewPhiMessage);
}
//local method
public void sendIncrease()
{
IncreaseMessage increaseMessage = new IncreaseMessage();
increaseMessage.setCurrentRound(this.currentRound);
increaseMessage.setCurrentSubround(this.currentSubround);
increaseMessage.setIncrease(this.increase);
byte[] byteIncreaseMessage = SerializationUtils.serialize(increaseMessage);
this.processorContext.forward("IncreaseMessage", byteIncreaseMessage);
}
I want to make a documentListener that if I type in the JTextField : txt_ip4class and match regex of IPv4 format it will change the JComboBox : box_ip4class content.
If the content is changed (itemStateChanged), range of IP Class will be written down to JTextField : txt_rangeclass, and bit usage will be write down to `JTextField : txt_bitclass``*.
I have succeeded in this method, but with a classic method (using jButton), but I failed in this method using documentListener. Only JComboBox : box_ip4Class changed.
My code, applying documentListener to txt_ip4class:
txt_ip4class.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
logUpdate();
}
#Override
public void removeUpdate(DocumentEvent e) {
logUpdate();
}
#Override
public void changedUpdate(DocumentEvent e) {
logUpdate();
}
void logUpdate() {
Runnable doHighlight = new Runnable() {
#Override
public void run() {
String aTxt = txt_ip4class.getText();
classValue = 1;
if (!aTxt.matches("\\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.|$)){4}\\b")) {
classValue = 0;
} else if (aTxt.matches("\\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.|$)){4}\\b")) {
try {
classW.classMain(classValue, box_ip4class, txt_ip4class, txt_rangeclass, txt_bitclass);
} catch (IllegalStateException e) {
}
}
}
};
SwingUtilities.invokeLater(doHighlight);
}
});
classW.Main contains two conditions, if zero it will set other fields based on jComboBox (txt_ip4class will be replaced), if one it should be set jComboBox choosing an option. And from that option, it should do like option zero
Full code (I export these files from Netbeans project to zip):
Succeed method which using jButton to execute
Failed method which using documentListener without jButton
Full exception stacktrace is here
or
Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Attempt to mutate in notification
at javax.swing.text.AbstractDocument.writeLock(AbstractDocument.java:1338)
at javax.swing.text.AbstractDocument.replace(AbstractDocument.java:658)
at javax.swing.text.JTextComponent.setText(JTextComponent.java:1669)
at engines.ClassW.setFromCombo(ClassW.java:140)
at interfaces.Netgui$1.logUpdate(Netgui.java:63)
at interfaces.Netgui$1.insertUpdate(Netgui.java:41)
at javax.swing.text.AbstractDocument.fireInsertUpdate(AbstractDocument.java:201)
at javax.swing.text.AbstractDocument.handleInsertString(AbstractDocument.java:748)
at javax.swing.text.AbstractDocument.insertString(AbstractDocument.java:707)
at javax.swing.text.PlainDocument.insertString(PlainDocument.java:130)
at javax.swing.text.AbstractDocument.replace(AbstractDocument.java:669)
at javax.swing.text.JTextComponent.replaceSelection(JTextComponent.java:1328)
at javax.swing.text.DefaultEditorKit$DefaultKeyTypedAction.actionPerformed(DefaultEditorKit.java:884)
at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1663)
at javax.swing.JComponent.processKeyBinding(JComponent.java:2882)
at javax.swing.JComponent.processKeyBindings(JComponent.java:2929)
at javax.swing.JComponent.processKeyEvent(JComponent.java:2845)
at java.awt.Component.processEvent(Component.java:6310)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1954)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:806)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:1074)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:945)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:771)
at java.awt.Component.dispatchEventImpl(Component.java:4760)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
BUILD SUCCESSFUL (total time: 19 seconds)
===============EDIT 1============
Thanks to #MarkRotteveel
And this post
This problem is fixed, but another problem is exist..
Code in the doHighlight is running in a loop.
===============EDIT 2============
Updated the code.
doHighlight no longer looping when the condition doesn't equal the regex.
but still doing loop when the condition equals.
I have problem with saving object to output stream. I was reading something there and i tried to make FileChosser transient, but my IDE says, that it is not allowed here. All my classes implements Serializable, so I don't know, where is problem.
Here is error output:
java.io.NotSerializableException: javax.swing.plaf.metal.MetalFileChooserUI
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at javax.swing.event.EventListenerList.writeObject(EventListenerList.java:259)
at sun.reflect.GeneratedMethodAccessor8.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1028)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:441)
at javax.swing.JComponent.writeObject(JComponent.java:5515)
at sun.reflect.GeneratedMethodAccessor9.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1028)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:441)
at java.awt.Window.writeObject(Window.java:2937)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1028)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at java.awt.Window.writeObject(Window.java:2954)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1028)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at gui.ChessBoard.saveGame(ChessBoard.java:288)
at gui.ChessBoard$4.mouseClicked(ChessBoard.java:348)
at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:270)
at java.awt.Component.processMouseEvent(Component.java:6538)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6300)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4891)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4534)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Code has at least 20 classes, so I show you method where I think the problem is:
public void setListenerToSaveButton(JButton saveButton) {
saveButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
JFileChooser chooser = new JFileChooser();
chooser.setSelectedFile(new File("save.dat"));
int option = chooser.showSaveDialog(contentPane);
if (option == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
saveGame(file);
}
}
});
}
and here is saveGame method(Chessboard.java:288):
public void saveGame(File file) {
try {
ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(file));
stream.writeObject(this); // line 288
stream.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
I have simple client based on Jersey framework.
I want to use Genson as default JSON provider.
Firstly I created some class which implemented ContextResolver:
#Provider
public class GensonCustomResolver implements ContextResolver<Genson> {
private final Genson genson = new Genson.Builder().setSkipNull(true).setDateFormat(new UtcDateFormat()).create();
#Override
public Genson getContext(Class<?> type) {
return genson;
}
}
And UtcDateFormat class:
public class UtcDateFormat extends DateFormat {
#Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
return new StringBuffer("" + date.getTime());
}
#Override
public Date parse(String source, ParsePosition pos) {
return new Date(Long.parseLong(source));
}
}
Then I used this:
ClientConfig cfg = new DefaultClientConfig(GensonCustomResolver.class);
Client client = Client.create(cfg);
Integer meetingId = 1;
Meeting result = client.resource("http://mywebservise.com/").path("meeting")
.path(meetingId.toString()).get(ClientResponse.class).getEntity(Meeting.class);
But, it failed. Here are log:
javax.ws.rs.WebApplicationException: com.owlike.genson.TransformationException: Could not deserialize to property 'created' of class class com.mypack.model.Meeting
at com.owlike.genson.ext.jaxrs.GensonJsonConverter.readFrom(GensonJsonConverter.java:127)
at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:565)
at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:517)
at com.mypack.ws.MeetingsTest.getItem(MeetingsTest.java:159)
at com.mypack.ws.MeetingsTest.getItem(MeetingsTest.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:659)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:845)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1153)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
at org.testng.TestRunner.privateRun(TestRunner.java:771)
at org.testng.TestRunner.run(TestRunner.java:621)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:357)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:352)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:310)
at org.testng.SuiteRunner.run(SuiteRunner.java:259)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1199)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1124)
at org.testng.TestNG.run(TestNG.java:1032)
at org.gradle.api.internal.tasks.testing.testng.TestNGTestClassProcessor.stop(TestNGTestClassProcessor.java:110)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy2.stop(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:113)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:355)
at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:66)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
Caused by: com.owlike.genson.TransformationException: Could not deserialize to property 'created' of class class com.mypack.model.Meeting
at com.owlike.genson.reflect.PropertyMutator.couldNotDeserialize(PropertyMutator.java:56)
at com.owlike.genson.reflect.PropertyMutator.deserialize(PropertyMutator.java:39)
at com.owlike.genson.reflect.BeanDescriptor.deserialize(BeanDescriptor.java:116)
at com.owlike.genson.reflect.BeanDescriptor.deserialize(BeanDescriptor.java:98)
at com.owlike.genson.convert.NullConverter$NullConverterWrapper.deserialize(NullConverter.java:61)
at com.owlike.genson.Genson.deserialize(Genson.java:452)
at com.owlike.genson.ext.jaxrs.GensonJsonConverter.readFrom(GensonJsonConverter.java:125)
... 48 more
Caused by: com.owlike.genson.TransformationException: Could not parse date 1432800716000
at com.owlike.genson.convert.DefaultConverters$DateConverter.deserialize(DefaultConverters.java:824)
at com.owlike.genson.convert.DefaultConverters$DateConverter.deserialize(DefaultConverters.java:788)
at com.owlike.genson.convert.NullConverter$NullConverterWrapper.deserialize(NullConverter.java:61)
at com.owlike.genson.reflect.PropertyMutator.deserialize(PropertyMutator.java:37)
... 53 more
Caused by: java.text.ParseException: Unparseable date: "1432800716000"
at java.text.DateFormat.parse(DateFormat.java:357)
at com.owlike.genson.convert.DefaultConverters$DateConverter.read(DefaultConverters.java:830)
at com.owlike.genson.convert.DefaultConverters$DateConverter.deserialize(DefaultConverters.java:822)
... 56 more
What's wrong?
P.S. Jersey client 1.8
Genson 0.98
You should upgrade to the latest Genson version, there have been some improvements and providing a custom instance to jersey is easier.
In the newer versions, Genson will automatically detect if the input is the time in millis or a date string and deser it accordingly.
The dateformat registered with useDateFormat(...) will be used during deserialization, but this will also serialize the dates as strings. If you want to serialize them as a long (which is the default in the newever versions), you have define it with useDateAsTimestamp(true).
I hope this makes things a bit more clear. You can have a look at the config options for more details.
I am writing an application in Java and part of what it needs to do is serialize some objects so they can be imported later. When I wrote the serialization code, it did not work correctly. After much tinkering, I believe I have narrowed it down to only a few attributes and included the minimum possible code to trigger the error in this SSCEE:
import java.io.*;
import java.util.prefs.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
//main class
public class SerializeFail extends JFrame implements Serializable, ActionListener {
JMenuBar bar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem item = new JMenuItem("Click to Fail");
HashMap<String, Preferences> prefs = new HashMap<String, Preferences>();
public SerializeFail () {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
file.add(item);
bar.add(file);
item.addActionListener(this);
prefs.put("root", Preferences.userRoot().node(this.getClass().getName()));
setJMenuBar(bar);
pack();
setVisible(true);
}
//triggers the failure
public void actionPerformed (ActionEvent e) {
TestObject gr = new TestObject();
try {
FileOutputStream fileOutput = new FileOutputStream("testing.gradecalc");
ObjectOutputStream objectOutput = new ObjectOutputStream(fileOutput);
objectOutput.writeObject(gr);
fileOutput.close();
System.out.println("serialized");
} catch (FileNotFoundException fileNotFound) {
System.out.println("The file was not found");
fileNotFound.printStackTrace();
} catch (IOException io) {
System.out.println("There was some type of io exception");
System.out.println("Stack Trace");
io.printStackTrace();
System.out.println("Message Trace");
io.getMessage();
System.out.println("Cause Trace");
io.getCause();
}
}
public static void main(String[] args) {
new SerializeFail();
}
class TestObject implements Serializable {
int attribute;
public TestObject () {
attribute = 47;
}
}
}
The error I get's stack trace is:
There was some type of io exception
Stack Trace
java.io.NotSerializableException: com.apple.laf.AquaMenuBarBorder
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1181)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1541)
at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:439)
at javax.swing.JComponent.writeObject(JComponent.java:5525)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:988)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1429)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1175)
at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1375)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1171)
at java.io.ObjectOutputStream.access$300(ObjectOutputStream.java:162)
at java.io.ObjectOutputStream$PutFieldImpl.writeFields(ObjectOutputStream.java:1700)
at java.io.ObjectOutputStream.writeFields(ObjectOutputStream.java:479)
at java.awt.Container.writeObject(Container.java:3681)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:988)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1429)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1175)
at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1375)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1171)
at java.io.ObjectOutputStream.access$300(ObjectOutputStream.java:162)
at java.io.ObjectOutputStream$PutFieldImpl.writeFields(ObjectOutputStream.java:1700)
at java.io.ObjectOutputStream.writeFields(ObjectOutputStream.java:479)
at java.awt.Container.writeObject(Container.java:3681)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:988)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1429)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1175)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1541)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1506)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1429)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1175)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
at java.awt.AWTEventMulticaster.save(AWTEventMulticaster.java:946)
at java.awt.Component.writeObject(Component.java:8645)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
Message Trace
Cause Trace
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:988)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1429)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1175)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1541)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1506)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1429)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1175)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
at SerializeFail.actionPerformed(SerializeFail.java:34)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.AbstractButton.doClick(AbstractButton.java:376)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:833)
at com.apple.laf.AquaMenuItemUI.doClick(AquaMenuItemUI.java:157)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:877)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
On an interesting note, if the graphics related objects are eliminated such that the SSCEE is:
import java.io.*;
import java.util.prefs.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
//main class
public class SerializeFail implements Serializable {
HashMap<String, Preferences> prefs = new HashMap<String, Preferences>();
public SerializeFail () {
prefs.put("root", Preferences.userRoot().node(this.getClass().getName()));
TestObject gr = new TestObject();
try {
FileOutputStream fileOutput = new FileOutputStream("testing.gradecalc");
ObjectOutputStream objectOutput = new ObjectOutputStream(fileOutput);
objectOutput.writeObject(gr);
fileOutput.close();
System.out.println("serialized");
} catch (FileNotFoundException fileNotFound) {
System.out.println("The file was not found");
fileNotFound.printStackTrace();
} catch (IOException io) {
System.out.println("There was some type of io exception");
System.out.println("Stack Trace");
io.printStackTrace();
System.out.println("Message Trace");
io.getMessage();
System.out.println("Cause Trace");
io.getCause();
}
}
public static void main(String[] args) {
new SerializeFail();
}
class TestObject implements Serializable {
int attribute;
public TestObject () {
attribute = 47;
}
}
}
then the output (containing the stack trace of the exception) is:
There was some type of io exception
Stack Tracejava.io.NotSerializableException: java.util.prefs.MacOSXPreferences
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1181)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
at java.util.HashMap.writeObject(HashMap.java:1100)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:988)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1429)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1175)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1541)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1506)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1429)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1175)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1541)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1506)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1429)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1175)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
at SerializeFail.<init>(SerializeFail.java:16)
at SerializeFail.main(SerializeFail.java:35)
Message Trace
Cause Trace
I have looked around and researched serialization, but to no avail. Could someone please make it so the instance of TestObject serializes without fail with the graphics related components (first SSCEE) included because that is what the master application has (or at least point me in the right direction)?
Thank you. If there is anything else I can provide that would be of assistance, please just ask.
All of your non-static fields have to be either transient or transitively Serializable for the default serializer to work. In your case, the Apple look-and-feel and MacOSXPreferences, which are referenced by the fields you declare directly, aren't serializable.
Oddly enough, even though the Swing components all implement Serializable, the actual runtime implementations don't, and making Swing stuff Serializable is widely regarded to have been a mistake. Instead, you need to encapsulate the state (model) separately from the UI (view/controller). Serialize just the model object and have your client code rebuild the UI and then populate it from the saved model.
Similarly, Preferences is not Serializable, and so the runtime can't use default serialization for it. How you handle serializing the preferences depends on what you're trying to do; it's not clear from your example.