Skip to content

Instantly share code, notes, and snippets.

@zencd
Created May 6, 2023 18:41
Show Gist options
  • Save zencd/0d0cb522fa833fbdcdd6bff931bae37e to your computer and use it in GitHub Desktop.
Save zencd/0d0cb522fa833fbdcdd6bff931bae37e to your computer and use it in GitHub Desktop.
Resolve type argument of a Java generics typed field
@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