java Serializable interface has no function, why it affects “writeObject”/“readObject”
I checked that the interface of
Serializable
Has no function definition, yet when I define
private void readObject(ObjectOutputStream oos){
System.out.println("readObject!!");
}
private void writeObject(ObjectOutputStream oos){
System.out.println("writeObject!!");
}
function in a class, they're called while object is being serialized.
This is odd to me, if the interface defines these 2 functions, then I should override them to make sure they're called.
But in Serializable, how does compiler generate code that if I define my own "writeObject"/"readObject", they're called while serialization?
I tried to append
@Override
annotation on top of both functions, compiler reports error.
So how it works at all, would you help to give some explanations?
Thanks a lot!
java serialization serializable
add a comment |
I checked that the interface of
Serializable
Has no function definition, yet when I define
private void readObject(ObjectOutputStream oos){
System.out.println("readObject!!");
}
private void writeObject(ObjectOutputStream oos){
System.out.println("writeObject!!");
}
function in a class, they're called while object is being serialized.
This is odd to me, if the interface defines these 2 functions, then I should override them to make sure they're called.
But in Serializable, how does compiler generate code that if I define my own "writeObject"/"readObject", they're called while serialization?
I tried to append
@Override
annotation on top of both functions, compiler reports error.
So how it works at all, would you help to give some explanations?
Thanks a lot!
java serialization serializable
2
It's essentially a dirty hack. The serialisation mechanism searches for those methods by reflection.
– Boris the Spider
Nov 22 '18 at 15:35
The compiler has no idea there is a connection between the methods and the interfaces so if you get the name/signature incorrect, it is no help. Instead, the library looks for the method at runtime, and if it finds it, it will call them. In java 8 these methods could have been implemented usingdefaulthowever this wasn't available in Java 1.
– Peter Lawrey
Nov 22 '18 at 17:37
add a comment |
I checked that the interface of
Serializable
Has no function definition, yet when I define
private void readObject(ObjectOutputStream oos){
System.out.println("readObject!!");
}
private void writeObject(ObjectOutputStream oos){
System.out.println("writeObject!!");
}
function in a class, they're called while object is being serialized.
This is odd to me, if the interface defines these 2 functions, then I should override them to make sure they're called.
But in Serializable, how does compiler generate code that if I define my own "writeObject"/"readObject", they're called while serialization?
I tried to append
@Override
annotation on top of both functions, compiler reports error.
So how it works at all, would you help to give some explanations?
Thanks a lot!
java serialization serializable
I checked that the interface of
Serializable
Has no function definition, yet when I define
private void readObject(ObjectOutputStream oos){
System.out.println("readObject!!");
}
private void writeObject(ObjectOutputStream oos){
System.out.println("writeObject!!");
}
function in a class, they're called while object is being serialized.
This is odd to me, if the interface defines these 2 functions, then I should override them to make sure they're called.
But in Serializable, how does compiler generate code that if I define my own "writeObject"/"readObject", they're called while serialization?
I tried to append
@Override
annotation on top of both functions, compiler reports error.
So how it works at all, would you help to give some explanations?
Thanks a lot!
java serialization serializable
java serialization serializable
asked Nov 22 '18 at 15:33
TroskyvsTroskyvs
2,39721232
2,39721232
2
It's essentially a dirty hack. The serialisation mechanism searches for those methods by reflection.
– Boris the Spider
Nov 22 '18 at 15:35
The compiler has no idea there is a connection between the methods and the interfaces so if you get the name/signature incorrect, it is no help. Instead, the library looks for the method at runtime, and if it finds it, it will call them. In java 8 these methods could have been implemented usingdefaulthowever this wasn't available in Java 1.
– Peter Lawrey
Nov 22 '18 at 17:37
add a comment |
2
It's essentially a dirty hack. The serialisation mechanism searches for those methods by reflection.
– Boris the Spider
Nov 22 '18 at 15:35
The compiler has no idea there is a connection between the methods and the interfaces so if you get the name/signature incorrect, it is no help. Instead, the library looks for the method at runtime, and if it finds it, it will call them. In java 8 these methods could have been implemented usingdefaulthowever this wasn't available in Java 1.
– Peter Lawrey
Nov 22 '18 at 17:37
2
2
It's essentially a dirty hack. The serialisation mechanism searches for those methods by reflection.
– Boris the Spider
Nov 22 '18 at 15:35
It's essentially a dirty hack. The serialisation mechanism searches for those methods by reflection.
– Boris the Spider
Nov 22 '18 at 15:35
The compiler has no idea there is a connection between the methods and the interfaces so if you get the name/signature incorrect, it is no help. Instead, the library looks for the method at runtime, and if it finds it, it will call them. In java 8 these methods could have been implemented using
default however this wasn't available in Java 1.– Peter Lawrey
Nov 22 '18 at 17:37
The compiler has no idea there is a connection between the methods and the interfaces so if you get the name/signature incorrect, it is no help. Instead, the library looks for the method at runtime, and if it finds it, it will call them. In java 8 these methods could have been implemented using
default however this wasn't available in Java 1.– Peter Lawrey
Nov 22 '18 at 17:37
add a comment |
1 Answer
1
active
oldest
votes
java.io.Serializable is a functional interface, so that means it doesn't define any methods in it. @Override annotation is put if only you really wanna make sure noone will try to modify your overridden method. The reason you got a compiler error on @Override is that there is no such method in Serializable, but instead you can find them in ObjectInputStream and ObjectOutputStream (which use as a low-level classes FileInputStream and FileOutputStream respectively).
If you really wanna do Serialization on let's say, a list, you can do it like this:
package Chaper8.IO;
import java.io.*;
import java.util.*;
public class Serialization_Deserialization {
public static void main(String args){
/*
* try-catch with resources, JVM makes sure to close the resources after you've finished using it
* much easier than using finally and getting an exception for each resource closed
*
*/
try(FileOutputStream out = new FileOutputStream("C:\Users\Andrei\Desktop\Exemple\worker.txt");
ObjectOutputStream oos = new ObjectOutputStream(out);
FileInputStream in = new FileInputStream("C:\Users\Andrei\Desktop\Exemple\worker.txt");
ObjectInputStream ois = new ObjectInputStream(in);){
//instances of the Worker class
Worker w1 = new Worker("Worker1", 123456 , 2000.5);
Worker w2 = new Worker("Worker2", 765436, 1500.15);
Worker w3 = new Worker("Worker3", 364582, 1700.45);
Worker w4 = new Worker("Worker4", 878234, 2100.34);
ArrayList<Worker> list = new ArrayList<>();
//just adding the persons in the list
list.add(w1);
list.add(w2);
list.add(w3);
list.add(w4);
System.out.println("Doing serialization");
oos.writeObject(list);
System.out.println("Doing deserialization");
ois.readObject();
}catch(IOException | ClassNotFoundException e){
e.printStackTrace();
}
}
}
Worker.java
/*
* Worker class, basic type with variables, constructor, and toString() overridden
* Here I have implemented Serializable for the reason that I need to make sure that
* I will serialize the object within the class
*
* Note that I used transient for id. transient is a special keyword which makes sure
* that id will not be serialized, used for security reasons.
*
* serialVersionUID is another variable which is used during deserialization
* to verify that the sender and receiver of a serialized object have loaded
* classes for that object that are compatible with respect to serialization.
* Throws InvalidClassException if the object has a different serialVersionUID
* than that of the corresponding sender's class.
*
*/
import java.io.*;
class Worker implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private transient int id;
private double wage;
public Worker(String name, int id, double wage){
this.name = name;
this.id = id;
this.wage = wage;
}
public String toString(){
return "Person with name " +
name + " and with id " +
id + " has a salary of " + wage + "$";
}
}
1
Serializableis not a "functional interface". That term is used to describe an interface with exactly one abstract method (and is to be used as if it were just that one function). The phrase you are looking for is "marker interface". The alsoCloneableand thankfully few others.
– Tom Hawtin - tackline
Nov 25 '18 at 12:09
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53434207%2fjava-serializable-interface-has-no-function-why-it-affects-writeobject-reado%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
java.io.Serializable is a functional interface, so that means it doesn't define any methods in it. @Override annotation is put if only you really wanna make sure noone will try to modify your overridden method. The reason you got a compiler error on @Override is that there is no such method in Serializable, but instead you can find them in ObjectInputStream and ObjectOutputStream (which use as a low-level classes FileInputStream and FileOutputStream respectively).
If you really wanna do Serialization on let's say, a list, you can do it like this:
package Chaper8.IO;
import java.io.*;
import java.util.*;
public class Serialization_Deserialization {
public static void main(String args){
/*
* try-catch with resources, JVM makes sure to close the resources after you've finished using it
* much easier than using finally and getting an exception for each resource closed
*
*/
try(FileOutputStream out = new FileOutputStream("C:\Users\Andrei\Desktop\Exemple\worker.txt");
ObjectOutputStream oos = new ObjectOutputStream(out);
FileInputStream in = new FileInputStream("C:\Users\Andrei\Desktop\Exemple\worker.txt");
ObjectInputStream ois = new ObjectInputStream(in);){
//instances of the Worker class
Worker w1 = new Worker("Worker1", 123456 , 2000.5);
Worker w2 = new Worker("Worker2", 765436, 1500.15);
Worker w3 = new Worker("Worker3", 364582, 1700.45);
Worker w4 = new Worker("Worker4", 878234, 2100.34);
ArrayList<Worker> list = new ArrayList<>();
//just adding the persons in the list
list.add(w1);
list.add(w2);
list.add(w3);
list.add(w4);
System.out.println("Doing serialization");
oos.writeObject(list);
System.out.println("Doing deserialization");
ois.readObject();
}catch(IOException | ClassNotFoundException e){
e.printStackTrace();
}
}
}
Worker.java
/*
* Worker class, basic type with variables, constructor, and toString() overridden
* Here I have implemented Serializable for the reason that I need to make sure that
* I will serialize the object within the class
*
* Note that I used transient for id. transient is a special keyword which makes sure
* that id will not be serialized, used for security reasons.
*
* serialVersionUID is another variable which is used during deserialization
* to verify that the sender and receiver of a serialized object have loaded
* classes for that object that are compatible with respect to serialization.
* Throws InvalidClassException if the object has a different serialVersionUID
* than that of the corresponding sender's class.
*
*/
import java.io.*;
class Worker implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private transient int id;
private double wage;
public Worker(String name, int id, double wage){
this.name = name;
this.id = id;
this.wage = wage;
}
public String toString(){
return "Person with name " +
name + " and with id " +
id + " has a salary of " + wage + "$";
}
}
1
Serializableis not a "functional interface". That term is used to describe an interface with exactly one abstract method (and is to be used as if it were just that one function). The phrase you are looking for is "marker interface". The alsoCloneableand thankfully few others.
– Tom Hawtin - tackline
Nov 25 '18 at 12:09
add a comment |
java.io.Serializable is a functional interface, so that means it doesn't define any methods in it. @Override annotation is put if only you really wanna make sure noone will try to modify your overridden method. The reason you got a compiler error on @Override is that there is no such method in Serializable, but instead you can find them in ObjectInputStream and ObjectOutputStream (which use as a low-level classes FileInputStream and FileOutputStream respectively).
If you really wanna do Serialization on let's say, a list, you can do it like this:
package Chaper8.IO;
import java.io.*;
import java.util.*;
public class Serialization_Deserialization {
public static void main(String args){
/*
* try-catch with resources, JVM makes sure to close the resources after you've finished using it
* much easier than using finally and getting an exception for each resource closed
*
*/
try(FileOutputStream out = new FileOutputStream("C:\Users\Andrei\Desktop\Exemple\worker.txt");
ObjectOutputStream oos = new ObjectOutputStream(out);
FileInputStream in = new FileInputStream("C:\Users\Andrei\Desktop\Exemple\worker.txt");
ObjectInputStream ois = new ObjectInputStream(in);){
//instances of the Worker class
Worker w1 = new Worker("Worker1", 123456 , 2000.5);
Worker w2 = new Worker("Worker2", 765436, 1500.15);
Worker w3 = new Worker("Worker3", 364582, 1700.45);
Worker w4 = new Worker("Worker4", 878234, 2100.34);
ArrayList<Worker> list = new ArrayList<>();
//just adding the persons in the list
list.add(w1);
list.add(w2);
list.add(w3);
list.add(w4);
System.out.println("Doing serialization");
oos.writeObject(list);
System.out.println("Doing deserialization");
ois.readObject();
}catch(IOException | ClassNotFoundException e){
e.printStackTrace();
}
}
}
Worker.java
/*
* Worker class, basic type with variables, constructor, and toString() overridden
* Here I have implemented Serializable for the reason that I need to make sure that
* I will serialize the object within the class
*
* Note that I used transient for id. transient is a special keyword which makes sure
* that id will not be serialized, used for security reasons.
*
* serialVersionUID is another variable which is used during deserialization
* to verify that the sender and receiver of a serialized object have loaded
* classes for that object that are compatible with respect to serialization.
* Throws InvalidClassException if the object has a different serialVersionUID
* than that of the corresponding sender's class.
*
*/
import java.io.*;
class Worker implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private transient int id;
private double wage;
public Worker(String name, int id, double wage){
this.name = name;
this.id = id;
this.wage = wage;
}
public String toString(){
return "Person with name " +
name + " and with id " +
id + " has a salary of " + wage + "$";
}
}
1
Serializableis not a "functional interface". That term is used to describe an interface with exactly one abstract method (and is to be used as if it were just that one function). The phrase you are looking for is "marker interface". The alsoCloneableand thankfully few others.
– Tom Hawtin - tackline
Nov 25 '18 at 12:09
add a comment |
java.io.Serializable is a functional interface, so that means it doesn't define any methods in it. @Override annotation is put if only you really wanna make sure noone will try to modify your overridden method. The reason you got a compiler error on @Override is that there is no such method in Serializable, but instead you can find them in ObjectInputStream and ObjectOutputStream (which use as a low-level classes FileInputStream and FileOutputStream respectively).
If you really wanna do Serialization on let's say, a list, you can do it like this:
package Chaper8.IO;
import java.io.*;
import java.util.*;
public class Serialization_Deserialization {
public static void main(String args){
/*
* try-catch with resources, JVM makes sure to close the resources after you've finished using it
* much easier than using finally and getting an exception for each resource closed
*
*/
try(FileOutputStream out = new FileOutputStream("C:\Users\Andrei\Desktop\Exemple\worker.txt");
ObjectOutputStream oos = new ObjectOutputStream(out);
FileInputStream in = new FileInputStream("C:\Users\Andrei\Desktop\Exemple\worker.txt");
ObjectInputStream ois = new ObjectInputStream(in);){
//instances of the Worker class
Worker w1 = new Worker("Worker1", 123456 , 2000.5);
Worker w2 = new Worker("Worker2", 765436, 1500.15);
Worker w3 = new Worker("Worker3", 364582, 1700.45);
Worker w4 = new Worker("Worker4", 878234, 2100.34);
ArrayList<Worker> list = new ArrayList<>();
//just adding the persons in the list
list.add(w1);
list.add(w2);
list.add(w3);
list.add(w4);
System.out.println("Doing serialization");
oos.writeObject(list);
System.out.println("Doing deserialization");
ois.readObject();
}catch(IOException | ClassNotFoundException e){
e.printStackTrace();
}
}
}
Worker.java
/*
* Worker class, basic type with variables, constructor, and toString() overridden
* Here I have implemented Serializable for the reason that I need to make sure that
* I will serialize the object within the class
*
* Note that I used transient for id. transient is a special keyword which makes sure
* that id will not be serialized, used for security reasons.
*
* serialVersionUID is another variable which is used during deserialization
* to verify that the sender and receiver of a serialized object have loaded
* classes for that object that are compatible with respect to serialization.
* Throws InvalidClassException if the object has a different serialVersionUID
* than that of the corresponding sender's class.
*
*/
import java.io.*;
class Worker implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private transient int id;
private double wage;
public Worker(String name, int id, double wage){
this.name = name;
this.id = id;
this.wage = wage;
}
public String toString(){
return "Person with name " +
name + " and with id " +
id + " has a salary of " + wage + "$";
}
}
java.io.Serializable is a functional interface, so that means it doesn't define any methods in it. @Override annotation is put if only you really wanna make sure noone will try to modify your overridden method. The reason you got a compiler error on @Override is that there is no such method in Serializable, but instead you can find them in ObjectInputStream and ObjectOutputStream (which use as a low-level classes FileInputStream and FileOutputStream respectively).
If you really wanna do Serialization on let's say, a list, you can do it like this:
package Chaper8.IO;
import java.io.*;
import java.util.*;
public class Serialization_Deserialization {
public static void main(String args){
/*
* try-catch with resources, JVM makes sure to close the resources after you've finished using it
* much easier than using finally and getting an exception for each resource closed
*
*/
try(FileOutputStream out = new FileOutputStream("C:\Users\Andrei\Desktop\Exemple\worker.txt");
ObjectOutputStream oos = new ObjectOutputStream(out);
FileInputStream in = new FileInputStream("C:\Users\Andrei\Desktop\Exemple\worker.txt");
ObjectInputStream ois = new ObjectInputStream(in);){
//instances of the Worker class
Worker w1 = new Worker("Worker1", 123456 , 2000.5);
Worker w2 = new Worker("Worker2", 765436, 1500.15);
Worker w3 = new Worker("Worker3", 364582, 1700.45);
Worker w4 = new Worker("Worker4", 878234, 2100.34);
ArrayList<Worker> list = new ArrayList<>();
//just adding the persons in the list
list.add(w1);
list.add(w2);
list.add(w3);
list.add(w4);
System.out.println("Doing serialization");
oos.writeObject(list);
System.out.println("Doing deserialization");
ois.readObject();
}catch(IOException | ClassNotFoundException e){
e.printStackTrace();
}
}
}
Worker.java
/*
* Worker class, basic type with variables, constructor, and toString() overridden
* Here I have implemented Serializable for the reason that I need to make sure that
* I will serialize the object within the class
*
* Note that I used transient for id. transient is a special keyword which makes sure
* that id will not be serialized, used for security reasons.
*
* serialVersionUID is another variable which is used during deserialization
* to verify that the sender and receiver of a serialized object have loaded
* classes for that object that are compatible with respect to serialization.
* Throws InvalidClassException if the object has a different serialVersionUID
* than that of the corresponding sender's class.
*
*/
import java.io.*;
class Worker implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private transient int id;
private double wage;
public Worker(String name, int id, double wage){
this.name = name;
this.id = id;
this.wage = wage;
}
public String toString(){
return "Person with name " +
name + " and with id " +
id + " has a salary of " + wage + "$";
}
}
answered Nov 22 '18 at 17:24
Andrei PieleanuAndrei Pieleanu
463
463
1
Serializableis not a "functional interface". That term is used to describe an interface with exactly one abstract method (and is to be used as if it were just that one function). The phrase you are looking for is "marker interface". The alsoCloneableand thankfully few others.
– Tom Hawtin - tackline
Nov 25 '18 at 12:09
add a comment |
1
Serializableis not a "functional interface". That term is used to describe an interface with exactly one abstract method (and is to be used as if it were just that one function). The phrase you are looking for is "marker interface". The alsoCloneableand thankfully few others.
– Tom Hawtin - tackline
Nov 25 '18 at 12:09
1
1
Serializable is not a "functional interface". That term is used to describe an interface with exactly one abstract method (and is to be used as if it were just that one function). The phrase you are looking for is "marker interface". The also Cloneable and thankfully few others.– Tom Hawtin - tackline
Nov 25 '18 at 12:09
Serializable is not a "functional interface". That term is used to describe an interface with exactly one abstract method (and is to be used as if it were just that one function). The phrase you are looking for is "marker interface". The also Cloneable and thankfully few others.– Tom Hawtin - tackline
Nov 25 '18 at 12:09
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53434207%2fjava-serializable-interface-has-no-function-why-it-affects-writeobject-reado%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
It's essentially a dirty hack. The serialisation mechanism searches for those methods by reflection.
– Boris the Spider
Nov 22 '18 at 15:35
The compiler has no idea there is a connection between the methods and the interfaces so if you get the name/signature incorrect, it is no help. Instead, the library looks for the method at runtime, and if it finds it, it will call them. In java 8 these methods could have been implemented using
defaulthowever this wasn't available in Java 1.– Peter Lawrey
Nov 22 '18 at 17:37