RMI marshal and serialization - java

In java using RMI to marshal an object that you are returning from the remote class do you just need to implement Serializable on that object? I have a class node with variables inside that i want to be returned. Do i just implement serializable? If so what about the class that is receiving the object? does its class need to implement serializable too?
example:
public class node implements Serializable{
//variables
//variables
public node(//arguments to constructor here){
}
}

The class that is being serialized needs to implement Serializable. The sending and receiving classes don't. Not sure why you would think otherwise.

If you have a class whose instances you want to serialize using built-in Java serialization, not only must it implement Serializable, all its instance variables must also implement Serializable, or be primitives, or be marked transient (i.e. you tell the JVM that it's okay for them to not get serialized).
If your class can't conform to these constraints for some reason, you can implement custom serialization behavior yourself by implementing Externalizable - then you take responsibility for writing out your object's state and reading it back on the other end.

I'm not sure whether I understand your question correctly or not, but ... if the serializable class has other objects as member variables, then better make them serializable also, otherwise better declare as transient to skip. does this answer your question?
if code inspector program is handy, you can have answer for such question very quickly without posting it
for your tip, only the object you wan to persist or transfer needs to implements Serializable, so the object can be reconstructed as the class structure through serializing/unserializing

Related

Wondering if I need to implements serializable interface or not?

I am new to MyBatis, I saw some code which define model as
public class model implement serializable {
****
}
but some codes simple define without serializable interface.
I am wondering which is better? Serializable is an empty interface actually.
You need to define the Serializable interface if you plan to serialize instances of your class. It's that simple.
Many do it out of routine, but the entire point of Serializable is that some classes can NOT be serialized correctly. By making you implement this interface, you make the conscious decision that your class, in fact, can be serialized.
Mybatis don't require serialization. It dynamically calls constructor after executing query and create bean objects.
So answer is no you don't need to implement Serializable interface.
Serializable is a marker interface and has no method. It just tell jvm that you are intrested to serialize the type and rest will be done automatically.

Will objects of a custom class, inside an array, keep their data after serialization?

I am building a small application for keeping statistical data of some sort. I have a general question, before I start coding hard in this matter.
Say we have an object X of its own class, representing a sports match. It has several fields, among which is another object Y - also it's own class. Y will represent stats for a given game. The structure should be something like:
class Match {
Date date;
String venue;
ArrayList<Game>[10] gameList;
...
}
class Game{
int result;
int blah blah;
...
}
If I go and create a couple of Match objects, stored in an array for example, i can serialize an object, that contains this array of Matches, but when i deserialize it back, will I be able to keep the data inside the Game objects for example? Do I need to make each class used Serializable?
The reason for my worries are those lines from the JAVA Api Documentation:
During deserialization, the fields of non-serializable classes will
be initialized using the public or protected no-arg constructor of the
class. A no-arg constructor must be accessible to the subclass that is
serializable. The fields of serializable subclasses will be restored
from the stream.
When traversing a graph, an object may be encountered that does not
support the Serializable interface. In this case the
NotSerializableException will be thrown and will identify the class of
the non-serializable object.
Yes, you need to make Match class serializable. Making a class serialize means that you need to make all instance variables of that class serializable too (notice the recursive definition). In your example, to make Match class serializable, you need to make Game class serializable.
i guess the term
non-serializable classes
means such class doesn't implements the serializable interface there's exist classes in java doesn't implement serializable interface and you can't serialize them for example java.awt.BasicStroke you can't serialize any instance of of this class directly

Java: What can and what can't be serialized?

If the Serializable interface is just a Marker-Interface that is used for passing some-sort of meta-data about classes in java - I'm a bit confused:
After reading the process of java's serialization algorithm (metadata bottom-to-top, then actual instance data top-to-bottom), I can't really understand what data cannot be processed through that algorithm.
In short and formal:
What data may cause the NotSerializableException?
How should I know that I am not supposed to add the implements Serializable clause for my class?
First of all, if you don't plan to ever serialize an instance of your class, there is no need to even think about serializing it. Only implement what you need, and don't try to make your class serializable just for the sake of it.
If your object has a reference (transitive or direct) to any non-serializable object, and this reference is not marked with the transient keyword, then your object won't be serializable.
Generally, it makes no sense to serialize objects that can't be reused when deserialized later or somewhere else. This could be because the state of the object is only meaningful here and now (if it has a reference to a running thread, for example), or because it uses some resource like a socket, a database connection, or something like that. A whole lot of objects don't represent data, and shouldn't be serializable.
When you are talking about NotSerializableException it is throw when you want to serialize an object, which has not been marked as Serializable - that's all, although when you extend non serializable class, and add Serializable interface it is perfectly fine.
There is no data that can't be serialized.
Anything your Serializable class has in it that is not Serializable will throw this exception. You can avoid it by using the transient keyword.
Common examples of things you can't serialize include Swing components and Threads. If you think about it it makes sense because you could never deserialize them and have it make sense.
All the primitive data types and the classes extend either Serializable directly,
class MyClass extends Serializable{
}
or indirectly,
class MyClass extends SomeClass{
}
SomeClass implements Serializable.
can be serialized. All the fields in a serializable class gets serialized except the fields which are marked transient. If a serializable class contains a field which is not serializable(not primitive and do not extend from serializable interface) then NotSerializableException will be thrown.
Answer to the second question : As #JB Nizet said. If you are going to write the instance of a class to some stream then and then only mark it as Serializable, otherwise never mark a class Serializable.
You need to handle the serialization of your own Objects.
Java will handle the primitive data types for you.
More info: http://www.tutorialspoint.com/java/java_serialization.htm
After reading the process of java's serialization algorithm (metadata bottom-to- top, then actual instance data top-to-bottom), I can't really understand what data cannot be processed through that algorithm.
The answer to this is certain system-level classes such as Thread, OutputStream and its subclasses which are not serializable. Explained very well on the oracle documents: http://www.oracle.com/technetwork/articles/java/javaserial-1536170.html
Below is the abstract:
On the other hand, certain system-level classes such as Thread, OutputStream and its subclasses, and Socket are not serializable. Indeed, it would not make any sense if they were. For example, thread running in my JVM would be using my system's memory. Persisting it and trying to run it in your JVM would make no sense at all.
NotSerialisable exception is thrown when something in your serializable marked as serializable. One such case can be:
class Super{}
class Sub implements Serializable
{
Super super;
Here super is not mentioned as serializable so will throw NotSerializableException.
More practically, no object can be serialized (via Java's built-in
mechanism) unless its class implements the Serializable interface.
Being an instance of such a class is not a sufficient condition,
however: for an object to be successfully serialized, it must also be
true that all non-transient references it holds must be null or refer to
serializable objects. (Do note that that is a recursive condition.)
Primitive values, nulls, and transient variables aren't a problem.
Static variables do not belong to individual objects, so they don't
present a problem either.
Some common classes are reliably serialization-safe. Strings are
probably most notable here, but all the wrapper classes for primitive
types are also safe. Arrays of primitives are reliably serializable.
Arrays of reference types can be serialized if all their elements can be
serialized.
What data may cause the NotSerializableException?
In Java, we serialize object (the instance of a Java class which has already implemented the Serializable interface). So it's very clear that if a class has not implemented the Serializable interface, it cannot be serialized (then in that case NotSerializableException will be thrown).
The Serializable interface is merely a marker-interface, in a way we can say that it is just a stamp on a class and that just says to JVM that the class can be Serialized.
How should I know that I am not supposed to add the implements
Serializable clause for my class?
It all depends on your need.
If you want to store the Object in a database, you can
serialize it to a sequence of byte and can store it in the
database as persistent data.
You can serialize your Object to be used by other JVM working
on different machine.

Java Serialization and JavaBeans

Quick question, when marking an object as serializable, does it need to be a JavaBean? I mean, can you serialize an object that's not a JavaBean? Does it have any risk? Is it a good practice to always make an object a JavaBean if you intend to serialize it?
You are looking at it the wrong way. A Java Bean is any class that is
1) implements Serializable
2) Has a no-arg constructor
3) Has private members and setters/getters
So your question
marking an object as serializable, does it need to be a JavaBean?
has it backwards. Any class can be Serializable, by implementing the interface. Not all serializable classes define a Java Bean.
I mean, can you serialize an object that's not a JavaBean?
Yes.
Is it a good practice to always make an object a JavaBean if you
intend to serialize it?
It is good practice to design your classes with data encapsulation in mind. This means limiting access to fields directly, and using setters and getters where appropriate.
Of course, having a public no-arg constructor is not always necessary from an API point of view.
You really only need to follow the Java bean standard if you are going to use a library that depends on your classes being Java Beans.
Serializable is a marker Interface. Each Object you mark with the serializable interface can be sent trouh the wire or can be safed in a file. For example if you mark the class Foo with the serializable interface, you are able to safe the object state in a file and restore it later:
public class Foo implements java.io.Serializable{
public String name;
}
public main(){
Foo foo = new Foo();
foo.name="test";
try
{
FileOutputStream fileOut = new FileOutputStream("foo.file");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(foo);
}
}
That means it doesnt need to be a JavaBean. It could be a plain old java object, like the Foo Object example.
If you want to serialize an object of class, then that class need to implement serializable interface irrespective of it's bean (or) class with simple properties.
To serialize an object means to convert its state to a byte stream so that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implements either the java.io.Serializable interface or its subinterface, java.io.Externalizable. Deserialization is the process of converting the serialized form of an object back into a copy of the object
This tutorial may help you
You can serialize any object that implements the Serializable interface, whether it's a JavaBean or not.
That said, the decision to make an object Serializable shouldn't be made lightly, because it locks in certain implementation details of the class thus reducing future flexibility.
See here for information on implementing Serializable.

Why does implementing Externalizable need a default public constructor?

We don't need it if we're implementing Serializable. So why this difference? How does it relate to the actual mechanism of Serialization?
A thorough explanation (although the grammar of the article might be improved) can be found on http://www.jusfortechies.com/java/core-java/externalization.php . The short answer, for future reference in case the linked page goes away:
Externalizable is an interface extending Serializable. Contrary to Serializable, though, objects are not restored by just reading the serialized bytestream, but the public constructor is called and only once the object is thus created, its state is restored. This makes restoring more efficient.
Edit: See also What is the difference between Serializable and Externalizable in Java? .
This is primarily used for caching purposes. In order to deserialize across streams, you will need to spell out how you want your object to be deserialized, hence the two methods provided by the contract in Externalizable interface: writeExternal and readExternal. Note that Externalizable extends Serializable, so you don't necessarily need to implement Serializable interface (although it's a marker interface and there are no methods to be actually implemented).
For a sample implementation, have a look at MimeType.
A public no-arg constructor is needed while using Externalizable interface.
Because in case of Serializable
readObject reads the required information from the ObjectInputStream
Serialization uses reflection mechanism to get the necessary fields and their corresponding values.
Serializable serializes all the data members (except static and transient).
But in case of Externalizable
No reflection mechanism used.
User doesn't serializes all data members.That's why to fetch values of the members which are not externalized public no arg constructor is required.

Categories