Cache if a class has a default instance (#2676)

This commit is contained in:
Richy 2023-12-11 15:07:10 +01:00 committed by GitHub
parent 0eca2eebd2
commit 2448d8372e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 3 deletions

View File

@ -143,8 +143,7 @@ public class StructureModifier<T> {
for (FieldAccessor accessor : fields) {
Field field = accessor.getField();
if (!field.getType().isPrimitive() && !Modifier.isFinal(field.getModifiers())) {
Object defaultInstance = DEFAULT_GENERATOR.getDefault(field.getType());
if (defaultInstance != null) {
if (DEFAULT_GENERATOR.hasDefault(field.getType())) {
requireDefaults.put(accessor, currentFieldIndex);
}
}

View File

@ -26,6 +26,8 @@ import javax.annotation.Nullable;
import java.lang.reflect.Constructor;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.logging.Level;
/**
@ -164,7 +166,19 @@ public class DefaultInstances implements InstanceProvider {
public <T> T getDefault(Class<T> type) {
return getDefaultInternal(type, registered, 0);
}
private final ThreadLocal<Map<Class<?>, Boolean>> cache = ThreadLocal.withInitial(WeakHashMap::new);
/**
* Determines if a given class has a default value.
*
* @param type - the class to check
* @return true if the class has a default value, false otherwise
*/
public boolean hasDefault(Class<?> type) {
return cache.get().computeIfAbsent(type, aClass -> getDefaultInternal(aClass, registered, 0) != null);
}
/**
* Retrieve the constructor with the fewest number of parameters.
* @param <T> Type