gemini-code-assist[bot] commented on code in PR #38271:
URL: https://github.com/apache/beam/pull/38271#discussion_r3139114092
##########
runners/spark/src/main/java/org/apache/beam/runners/spark/structuredstreaming/translation/helpers/EncoderFactory.java:
##########
@@ -31,15 +31,29 @@
import scala.reflect.ClassTag;
public class EncoderFactory {
- // default constructor to reflectively create static invoke expressions
+ // Resolve the Scala case-class primary constructor (the one with the most
parameters).
+ // Constructor ordering returned by Class.getConstructors() is JVM-defined
and not stable
+ // across Spark versions, so we pick the widest constructor explicitly and
then dispatch on
+ // parameter count below to pick the right argument shape per Spark version.
private static final Constructor<StaticInvoke> STATIC_INVOKE_CONSTRUCTOR =
- (Constructor<StaticInvoke>) StaticInvoke.class.getConstructors()[0];
+ primaryConstructor(StaticInvoke.class);
- private static final Constructor<Invoke> INVOKE_CONSTRUCTOR =
- (Constructor<Invoke>) Invoke.class.getConstructors()[0];
+ private static final Constructor<Invoke> INVOKE_CONSTRUCTOR =
primaryConstructor(Invoke.class);
private static final Constructor<NewInstance> NEW_INSTANCE_CONSTRUCTOR =
- (Constructor<NewInstance>) NewInstance.class.getConstructors()[0];
+ primaryConstructor(NewInstance.class);
+
+ @SuppressWarnings("unchecked")
+ private static <T> Constructor<T> primaryConstructor(Class<T> cls) {
+ Constructor<?>[] ctors = cls.getConstructors();
+ Constructor<?> widest = ctors[0];
Review Comment:

The current implementation assumes that `getConstructors()` will always
return at least one element. If it returns an empty array (for example, if all
public constructors were removed or made non-public in a future Spark version),
`ctors[0]` will throw an `ArrayIndexOutOfBoundsException`. Since the goal of
this PR is to improve robustness, adding a check with a descriptive error
message is recommended to avoid a cryptic crash during static initialization.
```java
Constructor<?>[] ctors = cls.getConstructors();
if (ctors.length == 0) {
throw new IllegalStateException("No public constructors found for " +
cls.getName());
}
Constructor<?> widest = ctors[0];
```
--
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: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]