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 22, 2024
1 parent a70848f commit bb0bd84
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
Expand Up @@ -26,20 +26,19 @@

import static java.util.Objects.requireNonNull;

import static org.jdbi.v3.core.mapper.reflect.ConstructorMapper.CONSTRUCTOR_CACHE;

class ConstructorInstanceFactory<T> extends InstanceFactory<T> {
private final Constructor<T> constructor;

private final Supplier<Type[]> typeSupplier;

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 +75,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 -> getTypeSupplier(ctor, defaultSupplier));
}

private static <T> Type[] getTypeSupplier(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
Expand Up @@ -75,6 +75,9 @@ public final class ConstructorMapper<T> implements RowMapper<T> {
+ "that your result set has the columns expected, annotate the "
+ "parameter names explicitly with @ColumnName, or annotate nullable parameters as @Nullable";


static final Map<Constructor, Type[]> CONSTRUCTOR_CACHE = new ConcurrentHashMap<>();

/**
* Use the only declared constructor to map a class.
*
Expand Down

0 comments on commit bb0bd84

Please sign in to comment.