Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing private variables in java

I have a question on serialization. If my class has private variables and there are no getters and setters, then how will the value of these variables be read by the Serialization API.

like image 365
Sid Avatar asked Nov 22 '10 12:11

Sid


People also ask

Can private variables be serialized in Java?

In Java, serialization is a concept using which we can write the state of an object into a byte stream so that we can transfer it over the network (using technologies like JPA and RMI). But, static variables belong to class therefore, you cannot serialize static variables in Java.

Can private variables be serialized?

Although it is not explicitly demonstrated in this example, all member variables of a class will be serialized—even variables marked as private. In this aspect, binary serialization differs from the XmlSerializer class, which only serializes public fields.

Which variables Cannot be serialized?

Static Variables: These variables are not serialized, So during deserialization static variable value will loaded from the class.

What does serializing mean Java?

To serialize an object means to convert its state to a byte stream so that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implements either the java. io. Serializable interface or its subinterface, java. io.


2 Answers

First, access permissions are the compile-time feature. the access is not controlled in runtime.

It may confuse you but try to do the following: create 2 versions of class A:

1

public class A {
    public foo() {
        System.out.println("hello");
    }
}

2

public class A {
    private foo() {
        System.out.println("hello");
    }
}

Now write class that calls new A().foo() and compile it with the first version of the class A. Then put the second version into classpath and run the application. It will work!

So, do not worry about the access permissions: they can always be bypassed.

If for instance you are using reflection to call private method foo() from you have to get the method and then call setAccessible(true):

Method m = A.class.getMethod("foo",
null); m.setAccessible(true);
m.invoke(new A(), null);

If we can access private methods from our code, be sure that JDK classes can do this even if they are written in java. BTW as far as I know standard java serialization is implemented as native code.

like image 171
AlexR Avatar answered Oct 11 '22 00:10

AlexR


The Serialization API doesn't worry about private variables. Its purpose is to convert your object to a binary representation in a file or some other kind of storage that can be reconstructed later.

Here is Java's serialization algorithm explained.

like image 24
darioo Avatar answered Oct 11 '22 01:10

darioo