简体   繁体   中英

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?

Android Studio/IntelliJ has a handful of options for configuring how the debugger displays the data. 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:

JOL (Java Object Layout) is the tiny toolbox to analyze object layout schemes in JVMs. These tools are using Unsafe, JVMTI, and Serviceability Agent (SA) heavily to decoder the actual object layout, footprint, and references. This makes JOL much more accurate than other tools relying on heap dumps, specification assumptions, etc.

As others have pointed out, the debug variables view in IDEA does not directly reflect the memory layout; it's just a GUI choice made by IntelliJ. 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. Both IntelliJ (for GUI) and GSON (for serialization) chose alphabetical order, because that's the most user-friendly.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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