1 /*
  2  * Copyright (c) 2019, 2024, 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 8320575
 27  * @summary reflection test for records
 28  * @build R10
 29  * @compile RecordReflectionTest.java
 30  * @run testng/othervm RecordReflectionTest
 31  */
 32 
 33 import java.lang.annotation.*;
 34 import java.lang.reflect.*;
 35 import java.util.List;
 36 import org.testng.annotations.*;
 37 import static org.testng.Assert.*;
 38 
 39 @Test
 40 public class RecordReflectionTest {
 41 
 42     class NoRecord {}
 43 
 44     record R1() {}
 45 
 46     record R2(int i, int j) {}
 47 
 48     record R3(List<String> ls) {}
 49 
 50     record R4(R1 r1, R2 r2, R3 r3) {}
 51 
 52     record R5(String... args) {}
 53 
 54     record R6(long l, String... args) implements java.io.Serializable {}
 55 
 56     record R7(String s1, String s2, String... args) {}
 57 
 58     record R8<A, B>(A a, B b) implements java.io.Serializable { }
 59 
 60     record R9(List<String> ls) {
 61         R9 {} // compact constructor, will contain a mandated parameter
 62     }
 63 
 64     /* record R10 is defined in an accompaning jcod file, defined as:
 65     record R10(List<String> ls) { // in this case there wasn't be any compact constructor and thus no mandated param
 66     }
 67     */
 68 
 69     record R11(int i, List<String> ls) {
 70         R11 {} // compact constructor, will contain mandated parameters
 71     }
 72 
 73     record R12(List<String> ls, int i) {
 74         R12 {} // compact constructor, will contain mandated parameters
 75     }
 76 
 77     record R13(List<String> ls1, int i, List<String> ls2) {
 78         R13 {} // compact constructor, will contain mandated parameters
 79     }
 80 
 81     @DataProvider(name = "recordClasses")
 82     public Object[][] recordClassData() {
 83         return List.of(R1.class,
 84                        R2.class,
 85                        R3.class,
 86                        R4.class,
 87                        R5.class,
 88                        R6.class,
 89                        R7.class,
 90                        R8.class,
 91                        R9.class,
 92                        R10.class,
 93                        R11.class,
 94                        R12.class,
 95                        R13.class
 96         ).stream().map(c -> new Object[] {c}).toArray(Object[][]::new);
 97     }
 98 
 99     @Test(dataProvider = "recordClasses")
100     public void testIsRecord(Class<?> cls) {
101         String message = cls.toGenericString();
102         assertTrue(cls.isRecord());
103         assertTrue(cls.getSuperclass() == java.lang.Record.class);
104         assertTrue(cls.getRecordComponents() != null);
105         assertTrue(message.contains("record"), message);
106     }
107 
108     @DataProvider(name = "notRecordClasses")
109     public Object[][] notRecordClasses() {
110         return List.of(NoRecord.class,
111                        NoRecord[].class,
112                        Record.class,  // java.lang.Record is not itself a record class
113                        Record[].class,
114                        byte.class,
115                        byte[].class,
116                        int.class,
117                        int[].class,
118                        long.class,
119                        long[].class)
120                    .stream().map(c -> new Object[] {c}).toArray(Object[][]::new);
121     }
122 
123     @Test(dataProvider = "notRecordClasses")
124     public void testNotARecordClass(Class<?> cls) {
125         assertFalse(cls.isRecord());
126         assertFalse(cls.getSuperclass() == java.lang.Record.class);
127         assertTrue(cls.getRecordComponents() == null);
128     }
129 
130     @DataProvider(name = "reflectionData")
131     public 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     @Test(dataProvider = "reflectionData")
185     public void testRecordReflection(Object recordOb,
186                                      int numberOfComponents,
187                                      Object[] values,
188                                      String[] names,
189                                      String[] signatures)
190         throws ReflectiveOperationException
191     {
192         Class<?> recordClass = recordOb.getClass();
193         assertTrue(recordClass.isRecord());
194         RecordComponent[] recordComponents = recordClass.getRecordComponents();
195         assertEquals(recordComponents.length, numberOfComponents);
196         int i = 0;
197         for (RecordComponent rc : recordComponents) {
198             assertEquals(rc.getName(), names[i]);
199             assertEquals(rc.getType(), rc.getAccessor().getReturnType());
200             assertEquals(rc.getAccessor().invoke(recordOb), values[i]);
201             assertEquals(rc.getAccessor().getGenericReturnType().toString(), signatures[i],
202                          String.format("signature of method \"%s\" different from expected signature \"%s\"",
203                                  rc.getAccessor().getGenericReturnType(), signatures[i]));
204             i++;
205         }
206         // now let's check constructors
207         var constructor = recordClass.getDeclaredConstructors()[0];
208         i = 0;
209         for (var p: constructor.getParameters()) {
210             assertEquals(p.getParameterizedType().toString(), signatures[i],
211                     String.format("signature of method \"%s\" different from expected signature \"%s\"",
212                             p.getType().toString(), signatures[i]));
213             i++;
214         }
215         // similar as above but testing another API
216         i = 0;
217         for (var p : constructor.getGenericParameterTypes()) {
218             assertEquals(p.toString(), signatures[i],
219                     String.format("signature of method \"%s\" different from expected signature \"%s\"",
220                             p.toString(), signatures[i]));
221             i++;
222         }
223     }
224 
225     @Retention(RetentionPolicy.RUNTIME)
226     @Target({ ElementType.RECORD_COMPONENT, ElementType.FIELD })
227     @interface RCA {}
228 
229     record AnnotatedRec(@RCA int i) {}
230 
231     public void testDeclAnnotationsInRecordComp() throws Throwable {
232         Class<?> recordClass = AnnotatedRec.class;
233         RecordComponent rc = recordClass.getRecordComponents()[0];
234         Annotation[] annos = rc.getAnnotations();
235         assertEquals(annos.length, 1);
236         assertEquals(annos[0].toString(), "@RecordReflectionTest.RCA()");
237 
238         Field f = recordClass.getDeclaredField("i");
239         assertEquals(f.getAnnotations().length, 1);
240         assertEquals(f.getAnnotations()[0].toString(), annos[0].toString());
241     }
242 
243     @Retention(RetentionPolicy.RUNTIME)
244     @Target({ElementType.TYPE_USE})
245     @interface TYPE_USE {}
246 
247     record TypeAnnotatedRec(@TYPE_USE int i) {}
248 
249     public void testTypeAnnotationsInRecordComp() throws Throwable {
250         Class<?> recordClass = TypeAnnotatedRec.class;
251         RecordComponent rc = recordClass.getRecordComponents()[0];
252         AnnotatedType at = rc.getAnnotatedType();
253         Annotation[] annos = at.getAnnotations();
254         assertEquals(annos.length, 1);
255         assertEquals(annos[0].toString(), "@RecordReflectionTest.TYPE_USE()");
256 
257         Field f = recordClass.getDeclaredField("i");
258         assertEquals(f.getAnnotatedType().getAnnotations().length, 1);
259         assertEquals(f.getAnnotatedType().getAnnotations()[0].toString(), annos[0].toString());
260     }
261 
262     public void testReadOnlyFieldInRecord() throws Throwable {
263         R2 o = new R2(1, 2);
264         Class<?> recordClass = R2.class;
265         String fieldName = "i";
266         Field f = recordClass.getDeclaredField(fieldName);
267         assertTrue(f.trySetAccessible());
268         assertTrue(f.get(o) != null);
269         try {
270             f.set(o, null);
271             assertTrue(false, "should fail to set " + fieldName);
272         } catch (IllegalAccessException e) {
273         }
274     }
275 }