1 /*
  2  * Copyright (c) 2019, 2026, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  */
 23 
 24 /*
 25  * @test
 26  * @bug 8235369 8235550 8247444 8326879 8320575
 27  * @summary reflection test for records
 28  * @build R10
 29  * @compile RecordReflectionTest.java
 30  * @run junit/othervm RecordReflectionTest
 31  * @run junit/othervm --enable-preview RecordReflectionTest
 32  */
 33 
 34 import java.lang.annotation.*;
 35 import java.lang.reflect.*;
 36 import java.util.List;
 37 import static org.junit.jupiter.api.Assertions.*;
 38 import org.junit.jupiter.api.Test;
 39 import org.junit.jupiter.params.ParameterizedTest;
 40 import org.junit.jupiter.params.provider.MethodSource;
 41 
 42 public class RecordReflectionTest {
 43 
 44     class NoRecord {}
 45 
 46     record R1() {}
 47 
 48     record R2(int i, int j) {}
 49 
 50     record R3(List<String> ls) {}
 51 
 52     record R4(R1 r1, R2 r2, R3 r3) {}
 53 
 54     record R5(String... args) {}
 55 
 56     record R6(long l, String... args) implements java.io.Serializable {}
 57 
 58     record R7(String s1, String s2, String... args) {}
 59 
 60     record R8<A, B>(A a, B b) implements java.io.Serializable { }
 61 
 62     record R9(List<String> ls) {
 63         R9 {} // compact constructor, will contain a mandated parameter
 64     }
 65 
 66     /* record R10 is defined in an accompaning jcod file, defined as:
 67     record R10(List<String> ls) { // in this case there wasn't be any compact constructor and thus no mandated param
 68     }
 69     */
 70 
 71     record R11(int i, List<String> ls) {
 72         R11 {} // compact constructor, will contain mandated parameters
 73     }
 74 
 75     record R12(List<String> ls, int i) {
 76         R12 {} // compact constructor, will contain mandated parameters
 77     }
 78 
 79     record R13(List<String> ls1, int i, List<String> ls2) {
 80         R13 {} // compact constructor, will contain mandated parameters
 81     }
 82 
 83     public static Object[][] recordClassData() {
 84         return List.of(R1.class,
 85                        R2.class,
 86                        R3.class,
 87                        R4.class,
 88                        R5.class,
 89                        R6.class,
 90                        R7.class,
 91                        R8.class,
 92                        R9.class,
 93                        R10.class,
 94                        R11.class,
 95                        R12.class,
 96                        R13.class
 97         ).stream().map(c -> new Object[] {c}).toArray(Object[][]::new);
 98     }
 99 
100     @ParameterizedTest
101     @MethodSource("recordClassData")
102     public void testIsRecord(Class<?> cls) {
103         String message = cls.toGenericString();
104         assertTrue(cls.isRecord());
105         assertSame(Record.class, cls.getSuperclass());
106         assertNotNull(cls.getRecordComponents());
107         assertTrue(message.contains("record"), message);
108     }
109 
110     public static List<Class<?>> notRecordClasses() {
111         return List.of(NoRecord.class,
112                        NoRecord[].class,
113                        Record.class,  // java.lang.Record is not itself a record class
114                        Record[].class,
115                        byte.class,
116                        byte[].class,
117                        int.class,
118                        int[].class,
119                        long.class,
120                        long[].class);
121     }
122 
123     @ParameterizedTest
124     @MethodSource("notRecordClasses")
125     public void testNotARecordClass(Class<?> cls) {
126         assertFalse(cls.isRecord());
127         assertNotSame(Record.class, cls.getSuperclass());
128         assertNull(cls.getRecordComponents());
129     }
130 
131     public static Object[][] reflectionData() {
132         return new Object[][] {
133             new Object[] { new R1(),
134                            0,
135                            null,
136                            null,
137                            null },
138             new Object[] { new R2(1, 2),
139                            2,
140                            new Object[]{ 1, 2 },
141                            new String[]{ "i", "j" },
142                            new String[]{ "int", "int"} },
143             new Object[] { new R3(List.of("1")),
144                            1,
145                            new Object[]{ List.of("1") },
146                            new String[]{ "ls" },
147                            new String[]{ "java.util.List<java.lang.String>"} },
148             new Object[] { new R4(new R1(), new R2(6, 7), new R3(List.of("s"))),
149                            3,
150                            new Object[]{ new R1(), new R2(6, 7), new R3(List.of("s")) },
151                            new String[]{ "r1", "r2", "r3" },
152                            new String[]{ R1.class.toString(), R2.class.toString(), R3.class.toString()} },
153             new Object[] { new R9(List.of("1")),
154                         1,
155                         new Object[]{ List.of("1") },
156                         new String[]{ "ls" },
157                         new String[]{ "java.util.List<java.lang.String>"} },
158             /* R10 has exactly the same definition as R9 but the parameter of the compact constructor doesn't have
159              * the mandated flag, nevertheless we should be able to load the same generic information
160              */
161             new Object[] { new R10(List.of("1")),
162                         1,
163                         new Object[]{ List.of("1") },
164                         new String[]{ "ls" },
165                         new String[]{ "java.util.List<java.lang.String>"} },
166             new Object[] { new R11(1, List.of("1")),
167                         2,
168                         new Object[]{ 1, List.of("1") },
169                         new String[]{ "i", "ls" },
170                         new String[]{ "int", "java.util.List<java.lang.String>"} },
171             new Object[] { new R12(List.of("1"), 1),
172                         2,
173                         new Object[]{ List.of("1"), 1 },
174                         new String[]{ "ls", "i" },
175                         new String[]{ "java.util.List<java.lang.String>", "int"} },
176             new Object[] { new R13(List.of("1"), 1, List.of("2")),
177                         3,
178                         new Object[]{ List.of("1"), 1, List.of("2") },
179                         new String[]{ "ls1", "i", "ls2" },
180                         new String[]{ "java.util.List<java.lang.String>", "int", "java.util.List<java.lang.String>"} },
181         };
182     }
183 
184     @ParameterizedTest
185     @MethodSource("reflectionData")
186     public void testRecordReflection(Object recordOb,
187                                      int numberOfComponents,
188                                      Object[] values,
189                                      String[] names,
190                                      String[] signatures)
191         throws ReflectiveOperationException
192     {
193         Class<?> recordClass = recordOb.getClass();
194         assertTrue(recordClass.isRecord());
195         RecordComponent[] recordComponents = recordClass.getRecordComponents();
196         assertEquals(numberOfComponents, recordComponents.length);
197         int i = 0;
198         for (RecordComponent rc : recordComponents) {
199             assertEquals(names[i], rc.getName());
200             assertEquals(rc.getAccessor().getReturnType(), rc.getType());
201             assertEquals(values[i], rc.getAccessor().invoke(recordOb));
202             assertEquals(signatures[i], rc.getAccessor().getGenericReturnType().toString(),
203                          String.format("signature of method \"%s\" different from expected signature \"%s\"",
204                                  rc.getAccessor().getGenericReturnType(), signatures[i]));
205             i++;
206         }
207         // now let's check constructors
208         var constructor = recordClass.getDeclaredConstructors()[0];
209         i = 0;
210         for (var p: constructor.getParameters()) {
211             assertEquals(signatures[i], p.getParameterizedType().toString(),
212                     String.format("signature of method \"%s\" different from expected signature \"%s\"",
213                             p.getType().toString(), signatures[i]));
214             i++;
215         }
216         // similar as above but testing another API
217         i = 0;
218         for (var p : constructor.getGenericParameterTypes()) {
219             assertEquals(signatures[i], p.toString(),
220                     String.format("signature of method \"%s\" different from expected signature \"%s\"",
221                             p.toString(), signatures[i]));
222             i++;
223         }
224     }
225 
226     @Retention(RetentionPolicy.RUNTIME)
227     @Target({ ElementType.RECORD_COMPONENT, ElementType.FIELD })
228     @interface RCA {}
229 
230     record AnnotatedRec(@RCA int i) {}
231 
232     @Test
233     public void testDeclAnnotationsInRecordComp() throws Throwable {
234         Class<?> recordClass = AnnotatedRec.class;
235         RecordComponent rc = recordClass.getRecordComponents()[0];
236         Annotation[] annos = rc.getAnnotations();
237         assertEquals(1, annos.length);
238         assertEquals("@RecordReflectionTest.RCA()", annos[0].toString());
239 
240         Field f = recordClass.getDeclaredField("i");
241         assertEquals(1, f.getAnnotations().length);
242         assertEquals(annos[0].toString(), f.getAnnotations()[0].toString());
243     }
244 
245     @Retention(RetentionPolicy.RUNTIME)
246     @Target({ElementType.TYPE_USE})
247     @interface TYPE_USE {}
248 
249     record TypeAnnotatedRec(@TYPE_USE int i) {}
250 
251     @Test
252     public void testTypeAnnotationsInRecordComp() throws Throwable {
253         Class<?> recordClass = TypeAnnotatedRec.class;
254         RecordComponent rc = recordClass.getRecordComponents()[0];
255         AnnotatedType at = rc.getAnnotatedType();
256         Annotation[] annos = at.getAnnotations();
257         assertEquals(1, annos.length);
258         assertEquals("@RecordReflectionTest.TYPE_USE()", annos[0].toString());
259 
260         Field f = recordClass.getDeclaredField("i");
261         assertEquals(1, f.getAnnotatedType().getAnnotations().length);
262         assertEquals(annos[0].toString(), f.getAnnotatedType().getAnnotations()[0].toString());
263     }
264 
265     @Test
266     public void testReadOnlyFieldInRecord() throws Throwable {
267         R2 o = new R2(1, 2);
268         Class<?> recordClass = R2.class;
269         String fieldName = "i";
270         Field f = recordClass.getDeclaredField(fieldName);
271         assertTrue(f.trySetAccessible());
272         assertNotNull(f.get(o));
273         assertThrows(IllegalAccessException.class, () -> f.set(o, null));
274     }
275 }