Java: Passing class as an argument for TypeReference

Viewed 543

I'm using the following code to create a map where the key is "String" and value are of type "SomeClass". How do I pass SomeClass as an argument so that I can reuse the function with multiple classes?

public Map<String, SomeClass> getMap(String mappingFilePath) throws IOException {
    Resource mappingResource = resourceLoader.getResource(mappingFilePath);
    return objectMapper.readValue(
        mappingResource.getInputStream(), new TypeReference<Map<String, SomeClass>>() {});
  }

For eg:

Map<String, Integer> tempMap = getMap(someFilePath, Integer)
// or
Map<String, SomeClass> tempMap = getMap(someFilePath, SomeClass)

Additional question:

Can we pass Map as the argument? So that in some cases, we can make it LinkedHashMap if needed.

Map<String, Integer> tempMap = getMap(someFilePath, Map<String, Integer>)
// or
Map<String, SomeClass> tempMap = getMap(someFilePath, LinkedHashMap<String, SomeClass>)
1 Answers

TypeReference is already a generic class, so you can taking it as second argument and return that type of object

public <T> T getMap(String mappingFilePath, TypeReference<T> typeReference) throws IOException {
Resource mappingResource = resourceLoader.getResource(mappingFilePath);
return objectMapper.readValue(
    mappingResource.getInputStream(), typeReference);
}

Then you can use it for any type

Map<String, Integer> tempMap = getMap(someFilePath, new TypeReference<Map<String, Integer>>() {})
// or
Map<String, SomeClass> tempMap = getMap(someFilePath, new TypeReference<Map<String, SomeClass>>() {})
Related