Created
May 6, 2023 18:41
-
-
Save zencd/0d0cb522fa833fbdcdd6bff931bae37e to your computer and use it in GitHub Desktop.
Resolve type argument of a Java generics typed field
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Target(ElementType.FIELD) | |
@Retention(RetentionPolicy.RUNTIME) | |
@interface TestPojo { | |
String file() | |
} | |
@TestPojo(file = "src/test/resources/foo-response.json") | |
FooResponse fooResponse | |
// invoke processSpecAnnotations() | |
static def processSpecAnnotations(Object objectWithAnno) { | |
for (Field field : objectWithAnno.getClass().declaredFields) { | |
TestPojo testPojo = field.getAnnotation(TestPojo) | |
if (testPojo) { | |
Object deserializedValue | |
if (List.class.isAssignableFrom(field.type)) { | |
def pt = (ParameterizedType) field.getGenericType() // like List<Foo> | |
assert pt.actualTypeArguments.size() == 1 | |
Class typeArg = (Class)pt.actualTypeArguments[0] // like Foo | |
JavaType javaType = objectMapper.getTypeFactory().constructCollectionType(List.class, typeArg) | |
deserializedValue = objectMapper.readValue(new File(testPojo.file()), javaType) | |
} else { | |
deserializedValue = objectMapper.readValue(new File(testPojo.file()), (Class)field.genericType) | |
} | |
assert deserializedValue != null | |
validatePojo(deserializedValue) | |
field.setAccessible(true) | |
field.set(spec, deserializedValue) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment