Serializing private variables in java

前端 未结 4 2174
一生所求
一生所求 2021-02-19 16:38

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 Serializat

相关标签:
4条回答
  • 2021-02-19 17:05

    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.

    0 讨论(0)
  • 2021-02-19 17:12

    The default serialization mechanism doesn't care about the access scope of member variables. In other words public, protected, package-private, and private variables are all treated in the same way. The implementation details might vary, but as I remember the Sun JRE does this by implementing much of the serialization in native (JNI) code where access privileges aren't enforced.

    0 讨论(0)
  • 2021-02-19 17:14

    Don't wory, by using the reflection anyone can access your's private fields.

    Here is an example how to do this.

    0 讨论(0)
  • 2021-02-19 17:17

    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.

    0 讨论(0)
提交回复
热议问题