Skip to content

Commit 0d4c214

Browse files
author
Thomas Draier
committed
Allows to defines a getInstance() method on TypeResolver/DataFetcher/Validators/DefaultValues..
1 parent 2d447d6 commit 0d4c214

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

src/main/java/graphql/annotations/processor/util/ReflectionKit.java

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818

1919
import java.lang.reflect.Constructor;
2020
import java.lang.reflect.InvocationTargetException;
21+
import java.lang.reflect.Method;
22+
import java.lang.reflect.Modifier;
2123

2224
/**
2325
* A package level helper in calling reflective methods and turning them into
@@ -26,8 +28,16 @@
2628
public class ReflectionKit {
2729
public static <T> T newInstance(Class<T> clazz) throws GraphQLAnnotationsException {
2830
try {
31+
try {
32+
Method getInstance = clazz.getMethod("getInstance", new Class<?>[0]);
33+
if (Modifier.isStatic(getInstance.getModifiers()) && clazz.isAssignableFrom(getInstance.getReturnType())) {
34+
return (T) getInstance.invoke(null);
35+
}
36+
} catch (NoSuchMethodException e) {
37+
// ignore, just call the constructor
38+
}
2939
return clazz.newInstance();
30-
} catch (InstantiationException | IllegalAccessException e) {
40+
} catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
3141
throw new GraphQLAnnotationsException("Unable to instantiate class : " + clazz, e);
3242
}
3343
}

src/test/java/graphql/annotations/GraphQLInterfaceTest.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,10 @@ public void noResolver() {
6969

7070
public static class Resolver implements TypeResolver {
7171

72+
public static Resolver getInstance() {
73+
return new Resolver();
74+
}
75+
7276
@Override
7377
public GraphQLObjectType getType(TypeResolutionEnvironment env) {
7478
try {

0 commit comments

Comments
 (0)