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

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))

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.


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();
        }

    }
}

Tags:

Java