Search code examples
genericsgroovyjvm

In Groovy, how to get the type of an "array of X" given a template type X


In the code below, theTest works, but theTest2 doesn't. I can't find what to write in the XXXXX placeholder so that i can get the type of an array of X given a template type X. Could you please help making this test pass by writting something in XXXXX?

import com.fasterxml.jackson.databind.ObjectMapper
import spock.lang.Specification

class TestClass {
    Integer integer
    String string
}

class TestGenerics extends Specification {
    String toBeParsed = '[{"integer":1, "string":"hello"},{"integer":2, "string":"world"}]'

    def theTest() {
        when:
            List<TestClass> parsed = parseList(toBeParsed, TestClass[])
        then:
            parsed.first() instanceof TestClass
    }

    private <T> List<T> parseList(String string, Class<T[]> clazz) {
        new ObjectMapper().readValue(string, clazz) as List<T>
    }

    def theTest2() {
        when:
            List<TestClass> parsed = parseList2(toBeParsed, TestClass)
        then:
            parsed.first() instanceof TestClass
    }

    private <T> List<T> parseList2(String string, Class<T> clazz) {
        new ObjectMapper().readValue(string, XXXXX) as List<T>
    }
}

Solution

  • You mean like

    new ObjectMapper().with { mapper ->
        mapper.readValue(
            string,
            mapper.getTypeFactory().constructArrayType(clazz)
        ) as List<T>
    }
    

    Not at a computer, but I hope that works...