Skip to content

Commit

Permalink
Add fast-path in BeanUtils#instantiateClass
Browse files Browse the repository at this point in the history
For no-args constructor.

See spring-projectsgh-24104
  • Loading branch information
stsypanov authored and sdeleuze committed Sep 26, 2022
1 parent 42ab1b7 commit edcc559
Showing 1 changed file with 27 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ConcurrentReferenceHashMap;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

Expand Down Expand Up @@ -188,11 +189,18 @@ public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws
try {
ReflectionUtils.makeAccessible(ctor);
if (KotlinDetector.isKotlinReflectPresent() && KotlinDetector.isKotlinType(ctor.getDeclaringClass())) {
if (ObjectUtils.isEmpty(args)) {
return KotlinDelegate.instantiateClass(ctor);
}
return KotlinDelegate.instantiateClass(ctor, args);
}
else {
int parameterCount = ctor.getParameterCount();
Assert.isTrue(args.length <= parameterCount, "Can't specify more arguments than constructor parameters");
if (parameterCount == 0) {
return ctor.newInstance();
}
Class<?>[] parameterTypes = ctor.getParameterTypes();
Assert.isTrue(args.length <= parameterTypes.length, "Can't specify more arguments than constructor parameters");
Object[] argsWithDefaultValues = new Object[args.length];
for (int i = 0 ; i < args.length; i++) {
if (args[i] == null) {
Expand Down Expand Up @@ -887,6 +895,24 @@ public static <T> T instantiateClass(Constructor<T> ctor, Object... args)
return kotlinConstructor.callBy(argParameters);
}

/**
* Instantiate a Kotlin class using provided no-arg constructor.
* @param ctor the constructor of the Kotlin class to instantiate
*/
public static <T> T instantiateClass(Constructor<T> ctor)
throws IllegalAccessException, InvocationTargetException, InstantiationException {

KFunction<T> kotlinConstructor = ReflectJvmMapping.getKotlinFunction(ctor);
if (kotlinConstructor == null) {
return ctor.newInstance();
}
List<KParameter> parameters = kotlinConstructor.getParameters();
Assert.isTrue(parameters.isEmpty(), "Default no-args constructor must have no params");
Map<KParameter, Object> argParameters = Collections.emptyMap();
return kotlinConstructor.callBy(argParameters);
}


}

}

0 comments on commit edcc559

Please sign in to comment.