Skip to content

Commit 754d434

Browse files
nyobeyrashk
authored andcommitted
Problem: schema field ordering is non-deterministic (Enigmatis#45) (Enigmatis#46)
Java reflection returns class methods and fields in undefined order Solution: sort methods and fields by name
1 parent a2b2f7d commit 754d434

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

src/main/java/graphql/annotations/GraphQLAnnotations.java

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,10 +44,12 @@
4444
import java.lang.reflect.Parameter;
4545
import java.util.Arrays;
4646
import java.util.Collections;
47+
import java.util.Comparator;
4748
import java.util.HashMap;
4849
import java.util.List;
4950
import java.util.Map;
5051
import java.util.Optional;
52+
import java.util.TreeMap;
5153
import java.util.function.Function;
5254
import java.util.stream.Collectors;
5355

@@ -149,7 +151,7 @@ public GraphQLInterfaceType.Builder getIfaceBuilder(Class<?> iface) throws Graph
149151
if (description != null) {
150152
builder.description(description.value());
151153
}
152-
for (Method method : iface.getMethods()) {
154+
for (Method method : getOrderedMethods(iface)) {
153155
boolean valid = !Modifier.isStatic(method.getModifiers()) &&
154156
method.getAnnotation(GraphQLField.class) != null;
155157
if (valid) {
@@ -222,7 +224,7 @@ public GraphQLObjectType.Builder getObjectBuilder(Class<?> object) throws GraphQ
222224
if (description != null) {
223225
builder.description(description.value());
224226
}
225-
for (Method method : object.getMethods()) {
227+
for (Method method : getOrderedMethods(object)) {
226228

227229
Class<?> declaringClass = getDeclaringClass(method);
228230

@@ -261,13 +263,19 @@ public static GraphQLObjectType.Builder objectBuilder(Class<?> object) throws Gr
261263
}
262264

263265

266+
protected List<Method> getOrderedMethods(Class c) {
267+
return Arrays.stream(c.getMethods())
268+
.sorted(Comparator.comparing(Method::getName))
269+
.collect(Collectors.toList());
270+
}
271+
264272
protected Map<String, Field> getAllFields(Class c) {
265273
Map<String, Field> fields;
266274

267275
if (c.getSuperclass() != null) {
268276
fields = getAllFields(c.getSuperclass());
269277
} else {
270-
fields = new HashMap<>();
278+
fields = new TreeMap<>();
271279
}
272280

273281
for (Field f : c.getDeclaredFields()) {

0 commit comments

Comments
 (0)