Reputation: 27203
I am doing some code review and came across serializable class that contains a non serializable field. That field is neither declared as transient. Can this kind of code be termed as a code smell. If yes then why?
public class A implements Serializable{
private B field ; // B is non serializable
}
Upvotes: 1
Views: 488
Reputation: 136042
It's not the field but the object this field points to may cause NotSerializableException.
E.g. if field
is null there will be no exception. Or if field
points to an instance of C which is a Serializable subclass of B there will be no exception.
Upvotes: 0
Reputation: 262584
This will make an exception when you try to serialize the object (unless the field is null, or the actual object is of a serializable subclass of B
).
You have to make it either transient or serializable (or implement your own serialization method).
Upvotes: 1
Reputation: 21883
This will result in an error if you try to serialize A
. Because B
is not Serializable. It is code smell.
Upvotes: -1
Reputation: 1501133
It will throw an exception when you try to serialize it, if the execution time type of the object isn't serializable.
For example, this does serialize:
import java.io.*;
public class Test implements Serializable {
private Object object;
public static void main(String[] args) throws Exception {
Test test = new Test();
test.object = "";
// Now serialize test
}
}
That will create an appropriate file - but if test.object
is set to new Object()
instead, then it will throw the exception.
It's not just a code smell - it's a bug, unless B
is an abstract class and all concrete subclasses are serializable... or if you know some other way that it will never be serialized unless the value of field
is serializable or null.
Upvotes: 5