Posts

Showing posts with the label java-record

Is there a way to recognise a Java 16 record's canonical constructor via reflection?

15 2 Assuming I have a record like this (or any other record): record X(int i, int j) { X(int i) { this(i, 0); } X() { this(0, 0); } X(String i, String j) { this(Integer.parseInt(i), Integer.parseInt(j)); } } Is there a way to find this record's canonical constructor via reflection, i.e. the one that is implicitly declared in the RecordHeader ? java reflection java-record java-16 Share Improve this question Fo...

How can I assert hasProperty with a Java Record?

11 3 I have a piece of code in a test that checks that a list of results contains certain properties, using Hamcrest 2.2: assertThat(result.getUsers(), hasItem( hasProperty("name", equalTo(user1.getName())) )); assertThat(result.getUsers(), hasItem( hasProperty("name", equalTo(user2.getName())) )); This worked perfectly fine when NameDto was a normal class. But after I changed it to a Record , Hamcrest's hasProperty complains about there being no property named name : java.lang.AssertionError: Expected: a collection containing hasProperty("name", "Test Name") but: mismatches were: [No property "name", No property "name"] Is there some other matcher I can use to achieve the same matching a...

Record cannot get parameter names from constructors?

10 3 Looking to see how to use Records with reflection under Java 16 (and 15 same behavior) public record RecordTest2(int id, int something, double total, LocalDateTime createdOn) { public RecordTest2(int id, int something, double total) { this(id, something, total, LocalDateTime.now()); } } Looking at the canonical constructor I do see the parameter names, but not in the other ones. var recordTest2 = new RecordTest2(1, 2, 3.0, LocalDateTime.now()); Class<?> objectClass = recordTest2.getClass(); Constructor<?>[] constructors = objectClass.getConstructors(); for (Constructor<?> con : constructors) { System.out.println(con.getName()); Parameter[] parameters = con.getParameters(); for (Parameter parameter : parameters) { ...