For a Java record, the accessor methods are generated automatically and match the component names directly, without the "get" or "is" prefix. You can get these methods using reflection in a few ways:
- Using
getRecordComponents() (introduced in Java 16):
public static void printRecordAccessors(Class<?> clazz) {
if (!clazz.isRecord()) {
throw new IllegalArgumentException("Not a record class");
}
RecordComponent[] components = clazz.getRecordComponents();
for (RecordComponent component : components) {
Method accessor = component.getAccessor();
System.out.println("Accessor method: " + accessor.getName());
}
}
- Alternatively, you can filter the declared methods:
public static List<Method> getRecordAccessors(Class<?> clazz) {
if (!clazz.isRecord()) {
throw new IllegalArgumentException("Not a record class");
}
return Arrays.stream(clazz.getDeclaredMethods())
.filter(method ->
method.getParameterCount() == 0 &&
!method.isSynthetic() &&
!Modifier.isStatic(method.getModifiers()) &&
method.getName().matches("^[a-z].*"))
.collect(Collectors.toList());
}
The first approach using getRecordComponents() is cleaner and more reliable since it specifically returns the record components and their corresponding accessor methods. The second approach works but requires more filtering to exclude other methods that might be present in the record.
Example usage:
record Person(String name, int age) {}
// Later...
Class<?> recordClass = Person.class;
RecordComponent[] components = recordClass.getRecordComponents();
for (RecordComponent component : components) {
System.out.println(component.getAccessor().getName()); // Prints "name" and "age"
}