3

I understand what these fields are and how to use them, but I'm wondering this:

How does the Java compiler actually handle special fields like this in its compilation step? Does it really look for variables just based on their name?

That seems very non-Java like... Other than serialVersionUID and serialPersistentFields, are there others?

0

2 Answers 2

6

Unfortunately, yes, these members are magically discovered by name, reflectively at runtime. (Actually, its worse; whether they are static or not, public or private, etc, fits into the lookup.) You are right, this isn't a good practice, and not very Java-like, but this is a legacy we are stuck with.

For the full list, see the serialization specification: https://docs.oracle.com/en/java/javase/11/docs/specs/serialization/index.html

Sign up to request clarification or add additional context in comments.

2 Comments

To be clear, this would provide the full list of fields referenced based on name that are part of Java serialization, and not any that are used in other contexts within the core Java libraries.
1

I'm wondering how the java compiler actually works special fields like this into its compilation step.

The compiler is not involved. Those fields are discovered at runtime by reflection.

Other than serialVersionUID and serialPersistentFields, are there others?

Well ... there are many other parts of the Java SE libraries that use reflection to find things. For example, object serialization uses reflection to determine if a class has a readObject or writeObject method. And then there is the SPI pattern where service provider classes (e.g. JDBC Driver classes) are located by searching the classpath. (It depends on what you mean by "non-Java like" ...)

I don't know if there are other special fields in the SE libraries, but the question is probably moot since application and 3rd-party code can do the same kind of thing anyway.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.