Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get all Record fields and its values via reflection in Java 17?

I had a class:

class A {
   public final Integer orgId;
}

I replaced it with the record in Java 17:

record A (Integer orgId) {
}

Also, I had a code that did a validation via reflection that is working with the regular class, but doesn't work with the Records:

Field[] fields = obj.getClass().getFields(); //getting empty array here for the record
for (Field field : fields) {
}

What would be the correct way to get the Record object fields and its values via reflection in Java 17?

like image 618
Dmitriy Dumanskiy Avatar asked Oct 13 '21 10:10

Dmitriy Dumanskiy


People also ask

How do you find the value of field using reflection?

Field. get(Object obj) method returns the value of the field represented by this Field, on the specified object. The value is automatically wrapped in an object if it has a primitive type.

What Are records in Java 17?

More information about records, including descriptions of the implicitly declared methods synthesized by the compiler, can be found in section 8.10 of The Java Language Specification . A record class is a shallowly immutable, transparent carrier for a fixed set of values, called the record components.

What is Java Lang reflect field?

The reflected field may be a class (static) field or an instance field. A Field permits widening conversions to occur during a get or set access operation, but throws an IllegalArgumentException if a narrowing conversion would occur.


1 Answers

You can use the following method:

RecordComponent[] getRecordComponents()

You can retrieve name, type, generic type, annotations, and its accessor method from RecordComponent.

Point.java:

record Point(int x, int y) { }

RecordDemo.java:

import java.lang.reflect.RecordComponent;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class RecordDemo {
    public static void main(String args[]) throws InvocationTargetException, IllegalAccessException {
        Point point = new Point(10,20);
        RecordComponent[] rc = Point.class.getRecordComponents();
        System.out.println(rc[0].getAccessor().invoke(point));
    }
}

Output:

10

Alternatively,

import java.lang.reflect.RecordComponent;
import java.lang.reflect.Field;

public class RecordDemo {
    public static void main(String args[]) 
            throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException {
        Point point = new Point(10, 20);
        RecordComponent[] rc = Point.class.getRecordComponents();      
        Field field = Point.class.getDeclaredField(rc[0].getAccessor().getName());  
        field.setAccessible(true); 
        System.out.println(field.get(point));
    }
}
like image 97
Arvind Kumar Avinash Avatar answered Oct 27 '22 01:10

Arvind Kumar Avinash