Describe the bug
When calling method JavaObjectTransformer.apply() on a class that has multiple constructors, including a no-argument one. Sometimes, when attempting to locate the no-argument constructor, it finds one of the others instead.
Here is a stack trace illustrating the exception that occurs:
java.lang.IllegalArgumentException: wrong number of arguments: 0 expected: 1
at java.base/jdk.internal.reflect.DirectConstructorHandleAccessor.newInstance(DirectConstructorHandleAccessor.java:59)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:502)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:486)
at net.datafaker.transformations.JavaObjectTransformer.apply(JavaObjectTransformer.java:61)
The problem occurs at line 61 of the JavaObjectTransformer. It calls c.getDeclaredConstructors()[0], but there is no guarantee that the 0th array element is the no-argument constructor.
To Reproduce
To reproduce, create a class with a no-argument constructor as well as a second constructor that takes an argument.
Then create a JavaObjectTransformer and attempt to apply a schema to the class you have created. Sometimes it will work fine, other times it will throw the exception.
Expected behavior
What should happen is the no-argument constructor should always be used in this section of the code in JavaObjectTransformer.
Versions:
- OS: Windows 11
- JDK: Oracle Java 21
- Faker Version 2.5.1
Additional context
The Java documentation is clear that the c.getDeclaredConstructors()[0] will not sort the array and can be returned in any order
https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Class.html#getDeclaredConstructors()