Thursday, 28 July 2022

How to get the record components in Java?

Records are classes to define immutable data. This is added as a preview feature in Jdk15. With records, we can create  immutable classes in a compact way.

public record Employee(int id, String name) {
    
}

 

The declaration of record specifies

a.  Name -> Employee

b.  Header -> (int id, String name)

c.  Body -> {}

 

Name specifies the record name, and header lists the components of the record, which are the variables that make up its state. We can access the record components using getRecordComponents() method available in java.lang.Class.

 


Point.java

package com.sample.app.reflections;

public record Point(int x, int y) {

}

 

RecordComponentsDemo.java

package com.sample.app.reflections;

import java.lang.reflect.RecordComponent;

public class RecordComponentsDemo {
    
    public static void main(String[] args) {
        RecordComponent[] recordComponents = Point.class.getRecordComponents();
        
        for(RecordComponent recordComponent: recordComponents) {
            System.out.println(recordComponent);
        }
    }

}

 

Output

int x
int y

 

References

https://openjdk.org/jeps/384

 


Previous                                                 Next                                                 Home

No comments:

Post a Comment