Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

EnumTypeAdapter constructor optimization #2734

Merged
merged 3 commits into from
Sep 3, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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