gyfora commented on code in PR #23490:
URL: https://github.com/apache/flink/pull/23490#discussion_r1367029934


##########
flink-core/src/main/java/org/apache/flink/api/java/typeutils/runtime/JavaRecordSerializationHelper.java:
##########
@@ -0,0 +1,151 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.api.java.typeutils.runtime;
+
+import org.apache.flink.annotation.Internal;
+
+import org.apache.flink.shaded.guava31.com.google.common.base.Defaults;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+
+/** Utilities for handling Java records nicely in the {@link PojoSerializer}. 
*/
+@Internal
+public class JavaRecordSerializationHelper<T> {
+
+    /** Record canonical constructor. Null for non-record classes. */
+    private final Constructor<T> recordConstructor;
+
+    private final boolean migrating;
+
+    /** Record constructor parameter index mapping for record migration. */
+    private final int[] paramIndexMapping;
+    /** Record constructor arg initializer, null when not needed. */
+    private final LinkedList<Consumer<Object[]>> arrayFieldInitializers;
+
+    public JavaRecordSerializationHelper(Constructor<T> recordConstructor) {
+        this(recordConstructor, false, null, null);
+    }
+
+    public JavaRecordSerializationHelper(
+            Constructor<T> recordConstructor,
+            boolean migrating,
+            int[] argIndexMapping,
+            LinkedList<Consumer<Object[]>> arrayFieldInitializers) {
+        this.recordConstructor = recordConstructor;
+        this.migrating = migrating;
+        this.paramIndexMapping = argIndexMapping;
+        this.arrayFieldInitializers = arrayFieldInitializers;
+    }
+
+    public void setParam(Object[] params, int i, Object field) {
+        if (migrating) {
+            params[paramIndexMapping[i]] = field;
+        } else {
+            params[i] = field;
+        }
+    }
+
+    public Object[] initParams() {
+        Object[] args = new Object[recordConstructor.getParameterCount()];
+        if (migrating) {
+            arrayFieldInitializers.forEach(c -> c.accept(args));
+        }
+        return args;
+    }
+
+    public T instantiateRecord(Object[] args) {
+        try {
+            return recordConstructor.newInstance(args);
+        } catch (Exception e) {
+            throw new RuntimeException("Could not instantiate record", e);
+        }
+    }
+
+    public static <T> JavaRecordSerializationHelper create(Class<T> clazz, 
Field[] fields) {
+        try {
+            Object[] recordComponents =
+                    (Object[]) 
Class.class.getMethod("getRecordComponents").invoke(clazz);
+
+            Class<?>[] componentTypes = new Class[recordComponents.length];
+            List<String> componentNames = new 
ArrayList<>(recordComponents.length);
+
+            // We need to use reflection to access record components as they 
are not available in
+            // Java 11
+            Method getType =
+                    
Class.forName("java.lang.reflect.RecordComponent").getMethod("getType");
+            Method getName =
+                    
Class.forName("java.lang.reflect.RecordComponent").getMethod("getName");
+            for (int i = 0; i < recordComponents.length; i++) {
+                componentNames.add((String) 
getName.invoke(recordComponents[i]));
+                componentTypes[i] = (Class<?>) 
getType.invoke(recordComponents[i]);
+            }
+            Constructor<T> recordConstructor = 
clazz.getDeclaredConstructor(componentTypes);
+            recordConstructor.setAccessible(true);
+
+            List<String> previousFields =
+                    Arrays.stream(fields)
+                            .filter(f -> f != null)
+                            .map(Field::getName)
+                            .collect(Collectors.toList());
+
+            // If the field names / order changed we know that we are 
migrating the records and arg
+            // index remapping may be necessary
+            boolean migrating = !previousFields.equals(componentNames);
+            if (migrating) {
+                // If the order / index of arguments changed in the new record 
class we have to map
+                // it, otherwise we pass the wrong arguments to the constructor
+                int[] argIndexMapping = new int[fields.length];
+                for (int i = 0; i < fields.length; i++) {
+                    Field field = fields[i];
+                    argIndexMapping[i] =
+                            field == null ? -1 : 
componentNames.indexOf(fields[i].getName());
+                }
+
+                // We have to initialize newly added primitive fields to their 
correct default value
+                LinkedList<Consumer<Object[]>> arrayFieldInitializers = new 
LinkedList<>();

Review Comment:
   Makes sense, simplifies the logic



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscr...@flink.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to