Skip to content

Commit 466354c

Browse files
committed
Cache list constructors to save on exceptions
1 parent 99504da commit 466354c

File tree

1 file changed

+23
-24
lines changed

1 file changed

+23
-24
lines changed

src/main/java/com/comphenix/protocol/wrappers/BukkitConverters.java

Lines changed: 23 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,7 @@
1717
package com.comphenix.protocol.wrappers;
1818

1919
import java.lang.ref.WeakReference;
20-
import java.lang.reflect.Array;
21-
import java.lang.reflect.Constructor;
22-
import java.lang.reflect.Field;
23-
import java.lang.reflect.Method;
24-
import java.lang.reflect.Modifier;
20+
import java.lang.reflect.*;
2521
import java.util.ArrayList;
2622
import java.util.Collection;
2723
import java.util.HashMap;
@@ -271,6 +267,8 @@ public Class<Map<K, V>> getSpecificType() {
271267
};
272268
}
273269

270+
private static Map<Class<?>, Supplier<List<Object>>> LIST_SUPPLIERS = new ConcurrentHashMap<>();
271+
274272
/**
275273
* Retrieve an equivalent converter for a list of generic items.
276274
* @param <T> Type
@@ -302,11 +300,26 @@ public List<T> getSpecific(Object generic) {
302300
@Override
303301
public Object getGeneric(List<T> specific) {
304302
List<Object> newList;
305-
306-
try {
307-
newList = (List<Object>) specific.getClass().newInstance();
308-
} catch (ReflectiveOperationException ex) {
309-
newList = new ArrayList<>();
303+
Supplier<List<Object>> supplier = LIST_SUPPLIERS.get(specific.getClass());
304+
if (supplier == null) {
305+
try {
306+
Constructor<?> ctor = specific.getClass().getConstructor();
307+
newList = (List<Object>) ctor.newInstance();
308+
supplier = () -> {
309+
try {
310+
return (List<Object>) ctor.newInstance();
311+
} catch (ReflectiveOperationException ex) {
312+
throw new RuntimeException(ex);
313+
}
314+
};
315+
} catch (ReflectiveOperationException ex) {
316+
supplier = ArrayList::new;
317+
newList = new ArrayList<>();
318+
}
319+
320+
LIST_SUPPLIERS.put(specific.getClass(), supplier);
321+
} else {
322+
newList = supplier.get();
310323
}
311324

312325
// Convert each object
@@ -363,20 +376,6 @@ public Class<Pair<A, B>> getSpecificType() {
363376
});
364377
}
365378

366-
/**
367-
* @deprecated While this solution is not as abhorrent as I had imagined, I still highly recommend switching to the
368-
* new conversion API.
369-
*/
370-
@Deprecated
371-
public static <T> EquivalentConverter<Set<T>> getSetConverter(final Class<?> genericType,
372-
final EquivalentConverter<T> itemConverter) {
373-
if (itemConverter instanceof EnumWrappers.EnumConverter) {
374-
((EnumWrappers.EnumConverter) itemConverter).setGenericType(genericType);
375-
}
376-
377-
return getSetConverter(itemConverter);
378-
}
379-
380379
/**
381380
* Retrieve an equivalent converter for a set of generic items.
382381
* @param <T> Element type

0 commit comments

Comments
 (0)