There're two class, one named Service, the other named Domain.
class Domain<T> {
String id;
// some other common fields and methods
T data;
T getData() {
return data;
}
class Service<T> {
T get(String id) {
// here's we need a Class<Domain<T>> to do some work
TypeToken<Domain<T>> typeToken = new TypeToken<Domain<T>>(getClass()){};
// how to get `Class<Domain<T>>` from `typeToken`
Class<Domain<T>> = ...
}
}
So, how to get Class<Domain<T>>
from TypeToken<Domain<T>>
?
For the record, asking "How do I retrieve a generic type from MongoTemplate.findOne()
?" would likely get you a much better answer .
The MongoTemplate
API doesn't accept TypeToken
or any other generic-capturing mechanism. That means it doesn't safely support returning generic types. Assuming you know at compile-time what the type should be you can do an unsafe cast, however:
Domain<T> domain = (Domain<T>) template.findOne(query, Domain.class);
Notice that this passes in Domain.class
, so findOne()
will return a raw Domain
instance, which then needs to be cast to Domain<T>
to avoid working with a raw type.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.