Tuesday, February 23, 2021

Reflection support for record classes

Two new methods are added to java.lang.Class to examine if a class or a Record class and if so, to find out its components. 

These two methods are 

1. isRecord - which returns a boolean indicating if the class is a record or not

2. getRecordComponents - which returns an array of java.lang.reflect.RecordComponent objects with each element representing a component of the record in the same order

Below sample code demonstrates the usage of these two methods

import java.lang.reflect.RecordComponent;

class Dog {
}

record Cat(String color) {
}

record Pair(Cat cat, Dog dog) {
}

class Main {

    public static void main(String[] args) {
        checkRecord(Dog.class);
        checkRecord(Cat.class);
        checkRecord(Pair.class);
    }

    private static void checkRecord(Class classToCheck) {
        System.out.println("\n" + classToCheck.getName() + " is a record class: " + classToCheck.isRecord());
        if (classToCheck.isRecord()) {
            System.out.print("Its components are: ");

            RecordComponent[] rComponents = classToCheck.getRecordComponents();
            for (RecordComponent component : rComponents) {
                System.out.print(component + ", ");
            }
            System.out.println();
        }

    }
}

In the above code, we have one regular class Dog and two record classes - Cat & Pair. 

While Cat has one component - color of type string, Pair has two components - Cat as the first component and Dog as its second component. 

The output of the above program is

Dog is a record class: false

Cat is a record class: true
Its components are: java.lang.String color,

Pair is a record class: true
Its components are: Cat cat, Dog dog,

As expected, for Cat and Pair, isRecord return true and its components gets printed.

java.lang.reflect.RecordComponent is a new class introduced in Java 14 to provide reflection access to record components. API documentation for this class is available at https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/reflect/RecordComponent.html    


Sample code used in this post can be downloaded from https://github.com/ashokkumarta/awesomely-java/tree/main/2021/02/Language-Features/Record/Reflection-support-for-record-classes

No comments:

Post a Comment