在java中序列化私有变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4245301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Serializing private variables in java
提问by Sid
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.
我有一个关于序列化的问题。如果我的类有私有变量并且没有 getter 和 setter,那么序列化 API 将如何读取这些变量的值。
采纳答案by darioo
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.
序列化 API 不担心私有变量。它的目的是将您的对象转换为文件中的二进制表示或稍后可以重建的其他类型的存储。
Hereis Java's serialization algorithm explained.
这里解释了 Java 的序列化算法。
回答by jutky
回答by AlexR
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:
它可能会让您感到困惑,但请尝试执行以下操作:创建 A 类的 2 个版本:
1
1
public class A {
public foo() {
System.out.println("hello");
}
}
2
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!
现在编写调用 new A().foo() 的类并使用类 A 的第一个版本编译它。然后将第二个版本放入类路径并运行应用程序。它会起作用!
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)
:
例如,如果您使用反射来调用私有方法foo()
,则必须获取该方法然后调用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.
如果我们可以从我们的代码中访问私有方法,请确保 JDK 类可以做到这一点,即使它们是用 java 编写的。顺便说一句,据我所知,标准 java 序列化是作为本机代码实现的。
回答by user320962
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.
默认的序列化机制不关心成员变量的访问范围。换句话说,public、protected、package-private 和 private 变量都以相同的方式处理。实现细节可能会有所不同,但我记得 Sun JRE 通过在未强制执行访问权限的本机 (JNI) 代码中实现大部分序列化来实现这一点。