简体   繁体   English

Java如何在内存中分配对象的属性?

[英]How does java allocate attributes of objects in memory?

I have a class that represents a set of attributes, but when serializing it I noticed these were re-ordered alphabetically. 我有一个代表一组属性的类,但是在对其进行序列化时,我注意到它们按字母顺序重新排序。 On investigation, this was because of how the attributes were being held in memory. 经调查,这是因为属性是如何保存在内存中的。

Class declaration: 类声明:

在此处输入图片说明

Objects in memory, before any serialization is done: 在完成任何序列化之前,内存中的对象:

在此处输入图片说明

Is this a "feature" of android studio running in Debug, or is something else going on? 这是Debug中运行的android studio的“功能”,还是发生了其他事情?

Android Studio/IntelliJ has a handful of options for configuring how the debugger displays the data. Android Studio / IntelliJ具有一些用于配置调试器如何显示数据的选项。 This is described in the docs for Variables pane . “变量”窗格的文档中对此进行了描述。 The sorting is controlled by Sort Values Alphabetically option in the Debug Tool Window . 排序由“调试工具”窗口中的“按字母顺序排序值”选项控制。

This is purely cosmetic and unrelated to actual object layout in memory. 这纯粹是装饰性的,与内存中的实际对象布局无关。 Java comes with JOL tool but I'm not sure it will work in Android: Java附带了JOL工具,但我不确定它是否可以在Android中使用:

JOL (Java Object Layout) is the tiny toolbox to analyze object layout schemes in JVMs. JOL(Java对象布局)是用于分析JVM中的对象布局方案的微型工具箱。 These tools are using Unsafe, JVMTI, and Serviceability Agent (SA) heavily to decoder the actual object layout, footprint, and references. 这些工具大量使用Unsafe,JVMTI和Serviceability Agent(SA)来解码实际的对象布局,覆盖区和引用。 This makes JOL much more accurate than other tools relying on heap dumps, specification assumptions, etc. 这使JOL比依赖堆转储,规范假设等的其他工具更加准确。

As others have pointed out, the debug variables view in IDEA does not directly reflect the memory layout; 正如其他人指出的那样,IDEA中的调试变量视图并不直接反映内存布局;它只是直接反映了内存布局。 it's just a GUI choice made by IntelliJ. 这只是IntelliJ做出的GUI选择。 You should generally not think of variables having any kind of order. 通常,您不应该考虑具有任何顺序的变量。 The order in which you put them in the source code is irrelevant. 将它们放在源代码中的顺序无关紧要。

Since there is no order to the fields, and since the JSON spec also states that fields aren't ordered, GSON is free to choose an ordering for serialization. 由于字段没有顺序,并且由于JSON规范也规定字段未排序,因此GSON可以自由选择序列化的顺序。 Both IntelliJ (for GUI) and GSON (for serialization) chose alphabetical order, because that's the most user-friendly. IntelliJ(用于GUI)和GSON(用于序列化)都选择了字母顺序,因为这是最易于使用的。

If you must have a different order in JSON (maybe because your data is consumed by software that violates the JSON spec by depending on a certain order), see this answer 如果您在JSON中必须具有不同的顺序(可能是因为您的数据被违反特定顺序的JSON规范的软件所占用),请参见此答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM