I found that Object class
in java is not serializable in java at the end when i've wasted much time for a problem.
So can anybody knows another class's those are not serializable or any way to check whether that class is serializable?
You can determine whether an object is serializable at run time by retrieving the value of the IsSerializable property of a Type object that represents that object's type.
A Java object is serializable if its class or any of its superclasses implements either the java. io. Serializable interface or its subinterface, java.
Certain system-level classes such as Thread , OutputStream and its subclasses, and Socket are not serializable. If you serializable class contains such objects, it must mark then as "transient".
What happens if you try to send non-serialized Object over network? 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
if (yourObjectInstance instanceof Serializable) {
// It is
} else {
// It is not
}
Note that if yourObjectInstance
is null
, that would enter the else
part as null
is not Serializable
, no matter what class the reference is about.
Also as Victor Sorokin points out, having a class implements Serializable
doesn't mean it can actually be serialized.
If an object is serializable, you should be able to convert it to a byte array. So you can use this test method and make sure that it does not throw an exception when you serialize it.
@Test
public void testIfYourClassIsSerilaizable() {
boolean exceptionThrown = false;
try {
YourClass obj = new YourClass();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
byte [] data = bos.toByteArray();
} catch(IOException ex) {
exceptionThrown = true;
}
Assert.assertFalse(exceptionThrown);
}
So based on that , if YourClass or its attributes do not implement Serializable, the above test will throw an exception, making the class not serializable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With