Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to check whether an object is serializable or not in java?

Tags:

java

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?

like image 528
Jaykishan Avatar asked Nov 29 '13 12:11

Jaykishan


People also ask

How do you know if an object is serialized?

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.

Is object serializable Java?

A Java object is serializable if its class or any of its superclasses implements either the java. io. Serializable interface or its subinterface, java.

What objects are not serializable in 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 object is not serialized in Java?

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.


2 Answers

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.

like image 71
m0skit0 Avatar answered Oct 05 '22 22:10

m0skit0


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.

like image 32
mykey Avatar answered Oct 06 '22 00:10

mykey