Skip to content

Commit 42290bc

Browse files
committed
Fixes to Object Factory as to throw ConstructorNotFoundException instead of NullPointerException
1 parent e8fa6d3 commit 42290bc

1 file changed

Lines changed: 8 additions & 2 deletions

File tree

bellatrix.core/src/main/java/solutions/bellatrix/core/utilities/ObjectFactory.java

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,12 @@ private static <T> Constructor<T> getSuitableConstructor(Class<T> clazz, Object[
3737
var argumentTypes = getArgumentTypes(arguments);
3838

3939
try {
40-
return (Constructor<T>)findConstructorMatch(clazz, argumentTypes);
40+
return findConstructorMatch(clazz, argumentTypes);
4141
} catch (NoSuchMethodException e) {
42+
if (argumentTypes == null || argumentTypes.length == 0) {
43+
throw new ConstructorNotFoundException();
44+
}
45+
4246
var types = new StringBuilder();
4347
for (var type : argumentTypes) {
4448
types.append(type.getName() + System.lineSeparator());
@@ -73,7 +77,7 @@ private static <T> Constructor<T> findVarArgsConstructor(Class clazz, Class[] ar
7377
args[args.length - 1] = getVarArgsType(clazz, argumentTypes);
7478

7579
return clazz.getDeclaredConstructor(args);
76-
} catch (NoSuchMethodException ignored) {
80+
} catch (NoSuchMethodException|NullPointerException ignored) {
7781
}
7882

7983
throw new NoSuchMethodException("No matching constructor found for the provided argument types.");
@@ -113,7 +117,9 @@ public ConstructorNotFoundException(int numberOfTypes, String types) {
113117
Given argument types:\n%s
114118
""").formatted(numberOfTypes, types));
115119
}
120+
116121
public ConstructorNotFoundException() {
122+
super("No default constructor was found." + System.lineSeparator());
117123
}
118124

119125
public ConstructorNotFoundException(String message) {

0 commit comments

Comments
 (0)