Skip to content

Commit 2448d83

Browse files
authored
Cache if a class has a default instance (#2676)
1 parent 0eca2ee commit 2448d83

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

src/main/java/com/comphenix/protocol/reflect/StructureModifier.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -143,8 +143,7 @@ private static Map<FieldAccessor, Integer> generateDefaultFields(Collection<Fiel
143143
for (FieldAccessor accessor : fields) {
144144
Field field = accessor.getField();
145145
if (!field.getType().isPrimitive() && !Modifier.isFinal(field.getModifiers())) {
146-
Object defaultInstance = DEFAULT_GENERATOR.getDefault(field.getType());
147-
if (defaultInstance != null) {
146+
if (DEFAULT_GENERATOR.hasDefault(field.getType())) {
148147
requireDefaults.put(accessor, currentFieldIndex);
149148
}
150149
}

src/main/java/com/comphenix/protocol/reflect/instances/DefaultInstances.java

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@
2626
import java.lang.reflect.Constructor;
2727
import java.util.Collection;
2828
import java.util.List;
29+
import java.util.Map;
30+
import java.util.WeakHashMap;
2931
import java.util.logging.Level;
3032

3133
/**
@@ -164,7 +166,19 @@ public void setMaximumRecursion(int maximumRecursion) {
164166
public <T> T getDefault(Class<T> type) {
165167
return getDefaultInternal(type, registered, 0);
166168
}
167-
169+
170+
private final ThreadLocal<Map<Class<?>, Boolean>> cache = ThreadLocal.withInitial(WeakHashMap::new);
171+
172+
/**
173+
* Determines if a given class has a default value.
174+
*
175+
* @param type - the class to check
176+
* @return true if the class has a default value, false otherwise
177+
*/
178+
public boolean hasDefault(Class<?> type) {
179+
return cache.get().computeIfAbsent(type, aClass -> getDefaultInternal(aClass, registered, 0) != null);
180+
}
181+
168182
/**
169183
* Retrieve the constructor with the fewest number of parameters.
170184
* @param <T> Type

0 commit comments

Comments
 (0)