Java获取泛化类型

@Retention(RetentionPolicy.RUNTIME)
public @interface MongodbTable {
    String name();
}

public class AbstractMongoDao<T> {
    private Class<T> clazz;
    private String collectionName;

    @Autowired
    private MongoTemplate mongoTemplate;

    public AbstractMongoDao() {
        clazz = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        if(clazz.isAnnotationPresent(MongodbTable.class)){
            collectionName = clazz.getAnnotation(MongodbTable.class).name();
        }
    }

    public void insert(T t){
        mongoTemplate.insert(t, collectionName);
    }

    public List<T> findByPrefix(String rowKey){
        Query query = Query.query(Criteria.where("rowKey").is(rowKey));
        return mongoTemplate.find(query, clazz, collectionName);
    }
}

 

posted @ 2019-04-24 23:16  牧之丨  阅读(1255)  评论(0编辑  收藏  举报