Skip to content

Commit

Permalink
EnumTypeAdapter constructor optimization (#2734)
Browse files Browse the repository at this point in the history
* EnumTypeAdapter constructor optimization

* reuse the fields array

* add comment about the necessity of unconditionally trimming the fields array
  • Loading branch information
esaulpaugh committed Sep 3, 2024
1 parent 7c55d8b commit 4e4c2fd
Showing 1 changed file with 10 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
import java.io.IOException;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

Expand Down Expand Up @@ -59,17 +59,21 @@ private EnumTypeAdapter(final Class<T> classOfT) {
// Uses reflection to find enum constants to work around name mismatches for obfuscated
// classes
Field[] fields = classOfT.getDeclaredFields();
ArrayList<Field> constantFieldsList = new ArrayList<>(fields.length);
int constantCount = 0;
for (Field f : fields) {
// Filter out non-constant fields, replacing elements as we go
if (f.isEnumConstant()) {
constantFieldsList.add(f);
fields[constantCount++] = f;
}
}

Field[] constantFields = constantFieldsList.toArray(new Field[0]);
AccessibleObject.setAccessible(constantFields, true);
// Trim the array to the new length. Every enum type can be expected to have at least
// one declared field which is not an enum constant, namely the implicit $VALUES array
fields = Arrays.copyOf(fields, constantCount);

for (Field constantField : constantFields) {
AccessibleObject.setAccessible(fields, true);

for (Field constantField : fields) {
@SuppressWarnings("unchecked")
T constant = (T) constantField.get(null);
String name = constant.name();
Expand Down

0 comments on commit 4e4c2fd

Please sign in to comment.