12

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?

Jaykishan
  • 1,409
  • 1
  • 15
  • 26
  • 1
    http://stackoverflow.com/questions/766106/test-if-object-implements-interface This may help you – 8f7ca04d817b1696 Nov 29 '13 at 12:56
  • I've attempted to write a best-effort unit test to check an interface or class is fully remotable/serializable here: https://stackoverflow.com/a/51732244/2960236 – wu-lee Aug 07 '18 at 17:23

7 Answers7

14

Use

if(someObj instanceof Serializable) // recommended because it uses 
                                    // the byte code instruction INSTANCEOF

or

if(Serializable.class.isInstance(someObj))

Using Class.isInstance(someObj) makes sense if the Class should be replaceable at runtime.

For example:

Class<?> someClass == ....; // assign a class object reference dynamically
if(someClass.isInstance(someObj))
René Link
  • 48,224
  • 13
  • 108
  • 140
  • 2
    There's more to checking if something is serializable than checking it implements `Serializable`. Some classes which are serializable aren't `Serializable` (enums, `Date`, etc.). Some which are, aren't (for example, those which have non-serializable members). – wu-lee Aug 07 '18 at 09:56
  • @wu-lee well, first enums are serializable and implement `Serializable`see the javadoc: https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html. The same applies to `Date` (if you mean `java.util.Date`). The second point is the responsibility of the class's programmer. If you mark a class as `Serializable` you have to take care that all non transient instance fields are serializable too. Or you have to write your own serialization methods (writeObject, readObject). Take a look at http://www.oracle.com/technetwork/articles/java/javaserial-1536170.html – René Link Aug 07 '18 at 11:39
  • point taken about Date etc. However, I think the second point stands, and is why it is much harder to check if objects are serializable than your answer (the currently accepted one) suggests. It also takes more than simply testing that serialization works - for instance, I discover that fields whose type is not `Serializable` will in fact serialize if they are `null`, which can lead to an false sense of security and an unexpected exception at runtime if you don't notice this. – wu-lee Aug 07 '18 at 12:39
  • @wu-lee I understand your point of view. In my opinion a developer must take care about the javadoc as well and if I read the javadoc of Serializable it's clear to me what to do. But you are also right and things can be even more complex. E.g. imagine a class that has a field of type `java.util.List`. A `java.util.List` does not extend `Serializable`. Now it depends on the concrete list type that is set if it is serializable or not. Setting the field to a `ArrayList` will work. Other list implementation might not work. Like the lazy loading list that are set by a persistence framework. – René Link Aug 08 '18 at 06:47
11

Using just instanceof not 100% reliable, as following code demonstrates. Your best bet is to examine sources of classes you try to marshal, if you have them, or, if not, you may hope class vendor got this thing right.

class A {
    final int field;



/*
// uncomment this ctor to make class "more" serializable
    A()  {
        this.field = -1;
    }
*/


    A(int field) {
        this.field = field;
    }
}

class B extends A implements Serializable {

    B(int field) {
        super(field);
    }

    public String toString() {
        return "B{field=" + field + "}";
    }
}

class Test {
    public static void main(String[] args) {
        System.out.println(Serializable.class.isAssignableFrom(B.class));

        B b = new B(11);

        try {
            ByteArrayOutputStream bf = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bf);
            oos.writeObject(b);
            oos.close();

            ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bf.toByteArray()));
            Object o = ois.readObject();
            System.out.println(o.toString());
        } catch (Exception e) {
            System.out.println("Not exactly Serializable");
            e.printStackTrace();
        }

    }
}
Victor Sorokin
  • 11,878
  • 2
  • 35
  • 51
  • You're demonstrating that `implements Serializable` is not enough to actually serialize the object. You're totally correct, but I think this is not the question being asked (or OP has to be more concrete). – m0skit0 Nov 29 '13 at 13:22
  • You hit the nail on the head IMHO – Dagmar Jun 26 '18 at 09:25
6

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.

mykey
  • 1,943
  • 19
  • 13
5

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.

Community
  • 1
  • 1
m0skit0
  • 25,268
  • 11
  • 79
  • 127
2

Some people suggested instanceof operator but it does another thing: it returns false if the reference is null, even if the class implements Serializable! And this also applies to Class.isInstance(Object obj)

gyorgyabraham
  • 2,550
  • 1
  • 28
  • 46
  • 2
    But `Serializable.class.isInstance(null)` will also return false. It doesn't matter what the type of the variable declaration is. If the reference is null than `instanceof` and `Class.isInstance()` will return false. – René Link Nov 29 '13 at 13:05
  • 1
    `null` is not an object instance and thus it does not implement `Serializable`, so the behavior is totally correct. – m0skit0 Nov 29 '13 at 13:18
  • I did not say it's not correct. I just clarified it's behavior. When you have an isSerializable(Object obj) { } method, you have no guarantees that caller puts a null into it. – gyorgyabraham Nov 29 '13 at 14:53
0

You can check for

someObject instanceof Serializable

This will evaluate to true if someObject implements the Serializable interface

Dragondraikk
  • 1,659
  • 11
  • 21
-1

you can check class is searializable or not:

if(someObj instanceof Serializable)
vivek bhoraniya
  • 1,526
  • 2
  • 17
  • 36