Getting the Type from generic type parameter, Within a class
Guava makes it easier to get the type of a generic type parameter. I personally feel it's ugly to request the Class given through the generic interface <T>, even though the class should already be aware of it. Even though browsing seems to turn up that asking for Class<T> in your constructor seems like the most standard way.
protected Class<T> clazz;
protected final MongoTemplate mongoTemplate; protected ExtendedMongoTemplate(MongoTemplate mongoTemplate) { this.mongoTemplate = mongoTemplate; final TypeToken<? extends T> typeToken = new TypeToken<>(this.getClass()){}; final Type type = typeToken.getType(); if(type instanceof Class) { clazz = (Class<T>) type; } else { throw new RuntimeException(this.getClass() + ": failed to retrieve generic parameter
class in " + ExtendedMongoTemplate.class.getSimpleName() + "."); } } /** * if the present way of extracting the class from the generic parameter fails * this method can be used in the child's constructor. * @param clazz */protected void setClazz(Class<T> clazz) { this.clazz = clazz;}
Comments
Post a Comment