Skip to content

Commit

Permalink
Cache types in ConstructorMapper
Browse files Browse the repository at this point in the history
  • Loading branch information
elonazoulay committed Feb 23, 2024
1 parent a70848f commit 2da68e8
Showing 1 changed file with 12 additions and 7 deletions.
Expand Up @@ -19,6 +19,8 @@
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
import java.util.stream.Stream;

Expand All @@ -27,19 +29,18 @@
import static java.util.Objects.requireNonNull;

class ConstructorInstanceFactory<T> extends InstanceFactory<T> {
private final Constructor<T> constructor;
private static final Map<Constructor, Type[]> CONSTRUCTOR_CACHE = new ConcurrentHashMap<>();

private final Supplier<Type[]> typeSupplier;
private final Constructor<T> constructor;

ConstructorInstanceFactory(Constructor<T> constructor) {
super(constructor);
this.constructor = requireNonNull(constructor, "constructor is null");
this.typeSupplier = getTypeSupplier(constructor, super::getTypes);
}

@Override
Type[] getTypes() {
return typeSupplier.get();
return getTypes(constructor, super::getTypes);
}

@Override
Expand Down Expand Up @@ -76,13 +77,17 @@ private static <T> boolean isGenericInformationLost(Constructor<T> factory) {
return lossDetected;
}

private static <T> Supplier<Type[]> getTypeSupplier(Constructor<T> constructor, Supplier<Type[]> defaultSupplier) {
private static <T> Type[] getTypes(Constructor<T> constructor, Supplier<Type[]> defaultSupplier) {
return CONSTRUCTOR_CACHE.computeIfAbsent(constructor, ctor -> computeTypes(ctor, defaultSupplier));
}

private static <T> Type[] computeTypes(Constructor<T> constructor, Supplier<Type[]> defaultSupplier) {
if (isGenericInformationLost(constructor)) {
return () -> getFields(constructor)
return getFields(constructor)
.map(Field::getGenericType)
.toArray(Type[]::new);
}
return defaultSupplier;
return defaultSupplier.get();
}

private static <T> Stream<Field> getFields(Constructor<T> constructor) {
Expand Down

0 comments on commit 2da68e8

Please sign in to comment.