lundi 30 janvier 2023

Java Records Reflection and Synthetic Methods

Based on the older Java (7) Language Specifications (13.1.7):

Any constructs introduced by a Java compiler that do not have a corresponding construct in the source code must be marked as synthetic, except for default constructors, the class initialization method, and the values and valueOf methods of the Enum class.

On newer ones (Java (17) Language Specifications (13.1.7): ) that wording changes to:

A construct emitted by a Java compiler must be marked as synthetic if it does not correspond to a construct declared explicitly or implicitly in source code, unless the emitted construct is a class initialization method (JVMS §2.9).

I wonder how would this apply to the accesor methods created for the components of java Records (JEP 395)

For example

record ARecord(int a){}

would have a method int a() yet there is no code representing such method, according to the wording of the older JLS such method is added by the compiler so I would expect it to be synthetic but its not, as it can be corroborated by running the following 2 lines on JShell

jshell
|  Welcome to JShell -- Version 17.0.1
|  For an introduction type: /help intro

jshell> record ARecord(int a){}
|  created record ARecord

jshell> ARecord.class.getDeclaredMethod("a").isSynthetic();
$2 ==> false

jshell>

The reason I ask is because I would like to use reflection (or any other programmatic mean at runtime) to determine which elements on the class have a matching code structure, basically those have code representing them, meaning:

For the following code

record ARecord(int a){

  pubic void someMethod() {}

}

that entity would have 2 methods (a and someMethod), a has no code representing it and someMethod does, I need a way to differentiate those based on that criteria





Aucun commentaire:

Enregistrer un commentaire