Explaining invokedynamic. Records. Part VIII

alex_ber
2 min readSep 8, 2020

This is seventh part of mini-series of Explaining invokedynamic. This is the full list of all articles:

Introduction. Part I

Toy example. Part II

Bootstrap method . Part III

Number multiplication (almost) complete example. Part IV

Dynamical hashCode implementation. Part V

Java 9 String concatenation. Part VI

Lambda. Part VII

Records. Part VIII

Final notes. Part IX

Records

Records are a new preview feature in Java 14 providing a nice concise syntax to declare classes that are supposed to be dumb data holders.

You can read here (Records (preview language feature) section) for more details. Also, in part V I’m provided you most part of the implementation with explanation.

Here’s a simple record example:

public record Color(String name, int code) {}

Given this simple one-liner, Java compiler generates appropriate implementations for accessor methods, toString, equals, and hashcode.

In order to implement toString, equals, or hashcode, Java is using invokedynamic

The alternative solution is to find all record fields and generate the equals logic based on those fields at compile-time. The more we have fields, the lengthier the bytecode.

On the contrary, Java calls a bootstrap method to link the appropriate implementation at runtime. Therefore, the bytecode length would remain constant regardless of the number of fields.

https://www.baeldung.com/java-invoke-dynamic

So, for records, compilers emits bytecode that encoded all static parameters type, and actual parameters value for toString, equals, and hashcode.

Note: The bootstrap method in this case is not public. So, this may change without notice.

Currently, there is single bootstrap method for all methods. This is ObjectMethods#bootstrap (it revives methodName as one of it’s parameters, that it used to differentiate what method should be implemented).

--

--