springmongotemplateparameterized-types

MongoTemplate Find Parameterized Class


With MongoTemplate, I'm having trouble with the find method when using what I'm calling a Parameterized Type of an Object. I might not be accurate in how to describe this so I will give an example:

public class Animal<T> {
  private String name
  private T attributes
}

public class Dog {
  private Integer weight
  ...
}

So I have those stored in Mongo like:

{
  "name": "Bernese Mountain Dog"
  "attributes": {
     "weight": 100
  }
}

If it was stored as a Dog document, I would be able to do something like:

mongoTemplate.find(query, Dog.class)

And then get a List<Dog> returned. But if my return type is something like List<Animal<T>>, then if I try to do something like:

mongoTemplate.find(query, Animal.class)

that will give an error about not being able to convert it. This also is not possible code:

mongoTemplate.find(query, Animal<Dog>.class) 

because that's just bad syntax.

Thoughts?


Solution

  • What I finally found that works was:

    mongoTemplate.find(query, (Class<Animal<T>>)(Class<T>) Animal.class);
    

    It seems pretty wonky, but it worked. I do get warnings about the unchecked cast which I'm unable to sort out without suppressing them. If anyone has a better solution, please let me know.