Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions src/main/java/org/apache/ibatis/reflection/Reflector.java
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,10 @@ public Reflector(Type type) {
this.clazz = (Class<?>) type;
}
addDefaultConstructor(clazz);
Method[] classMethods = getClassMethods(clazz);
if (isRecord(clazz)) {
addRecordGetMethods(classMethods);
addRecordGetMethods(clazz);
} else {
Method[] classMethods = getClassMethods(clazz);
addGetMethods(classMethods);
addSetMethods(classMethods);
addFields(clazz);
Expand All @@ -94,9 +94,18 @@ public Reflector(Type type) {
}
}

private void addRecordGetMethods(Method[] methods) {
Arrays.stream(methods).filter(m -> m.getParameterTypes().length == 0)
.forEach(m -> addGetMethod(m.getName(), m, false));
private void addRecordGetMethods(Class<?> recordClass) {
Arrays.stream(recordClass.getDeclaredFields()).filter(field -> !Modifier.isStatic(field.getModifiers()))
.forEach(field -> {
try {
String fieldName = field.getName();
// record's get method and field have the same name
Method m = recordClass.getMethod(fieldName);
addGetMethod(fieldName, m, false);
} catch (NoSuchMethodException ignore) {
// A standard record can never throw this exception
}
});
}

private void addDefaultConstructor(Class<?> clazz) {
Expand Down
16 changes: 16 additions & 0 deletions src/test/java/org/apache/ibatis/reflection/ReflectorTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -406,4 +406,20 @@ public Foo<String> getFoo() {
assertEquals(Foo.class, setter.getRawType());
assertArrayEquals(new Type[] { String.class }, setter.getActualTypeArguments());
}

@Test
void shouldReflectRecord() throws Exception {
record User(Long id, String name, List<String> props) {
@SuppressWarnings("unused")
public int foo() {
return 1;
}
}

ReflectorFactory reflectorFactory = new DefaultReflectorFactory();
Reflector reflector = reflectorFactory.findForClass(User.class);
List<String> property = Arrays.asList(reflector.getGetablePropertyNames());
assertEquals(3, property.size());
assertTrue(property.containsAll(Arrays.asList("id", "name", "props")));
}
}