Can a transient field in a class be obtained using reflection

我的未来我决定 提交于 2020-01-02 02:01:11

问题


Can a transient field in a class be obtained using reflection? (using getDeclaredField(..))


回答1:


Yes, It is a normal field. You can check whether it is transient by:

Modifier.isTransient(field.getModifiers());

transient: A keyword in the Java programming language that indicates that a field is not part of the serialized form of an object. When an object is serialized, the values of its transient fields are not included in the serial representation, while the values of its non-transient fields are included.

So no logical reason for it not to be accessible by reflection. It's the value of the field that is ignored (sometimes), not the field itself.

(btw, what hindered you from just trying to call getDeclaredField("yourTransientField")?)




回答2:


transient indicates that the field will not be serialized. The field is still declared by the class, so it is fair game for reflection.




回答3:


Among all the objects that needs to be serialized there are those one that need not to be serialized. That's why this objects are marked with the keyword transient.




回答4:


transient fields have nothing to do with reflection. The keyword only signals that a field should be skipped during Java serialization process. So reflection can access transient fields just like any other fields.



来源:https://stackoverflow.com/questions/2256734/can-a-transient-field-in-a-class-be-obtained-using-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!