java 获取泛型T的class对象

发布时间:2023年12月17日

问题描述

最近在封装es方法的时候遇到一个问题,就是泛型T怎么获取对应的class对象,代码如下:

/**
 * @Author: hrd
 * @CreateTime: 2023/11/27 15:08
 * @Description:
 */
public interface IESIndex<R, P extends BaseModel> {

    /**
     *
     * @param p
     * @param id 唯一ID
     * @return
     */
    IndexResponse saveOrUpdateById(P p, String id);

    R list(R r);

    R getListByIds(String... ids);

    DeleteResponse deleteById(String id);

    BulkByScrollResponse deleteByQuery(QueryBuilder queryBuilder);

    @NotNull
    default String buildOrder() {
        return "createTime";
    }

    default QueryBuilder getQueryBuilder(P p) {
        return null;
    }
}
/**
 * @Author: hrd
 * @CreateTime: 2023/11/30 13:57
 * @Description:
 */
@Slf4j
@Component
@RequiredArgsConstructor
public abstract class ESIndexServer<T extends BaseModel> implements IESIndex<PageResult<T>, T> {


    private final RestHighLevelClient restHighLevelClient;

    protected abstract String getIndexName();


    @Override
    public IndexResponse saveOrUpdateById(T p, String id) {
        if (null == p || null == id || "".equals(id)) {
            return null;
        }
        IndexRequest request = new IndexRequest(this.getIndexName()).id(id);
        // 2.准备参数
        request.source(JSON.toJSONString(p), XContentType.JSON);
        try {
            IndexResponse index = restHighLevelClient.index(request, RequestOptions.DEFAULT);
            log.info("es:{}", index);
            return index;
        } catch (IOException e) {
            log.error("es:error", e);
        }
        return null;
    }


    @SuppressWarnings("unchecked")
    public Class<T> getTypeClass() {
        Type type = getClass().getGenericSuperclass();
        if (!(type instanceof ParameterizedType)) {
            throw new IllegalStateException("Type must be a parameterized type");
        }
        ParameterizedType parameterizedType = (ParameterizedType) type;
        // 获取泛型的具体类型  这里是单泛型
        Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
        if (null == actualTypeArguments || actualTypeArguments.length < 1) {
            throw new IllegalStateException("Number of type arguments must be 1");
        }
        return (Class<T>) actualTypeArguments[0];
    }


    @Override
    public PageResult<T> list(PageResult<T> pageResult) {
        SearchRequest request = new SearchRequest(this.getIndexName());
        // 2.准备请求参数
        // 2.2.分页
        buildQuery(pageResult.getQueryCondition(), request);
        int page = pageResult.getPage();
        int size = pageResult.getSize();
        request.source().from((page - 1) * size).size(size);
        String orderField = buildOrder();
        if (!StringUtils.isEmpty(orderField)) {
            request.source().sort(SortBuilders.fieldSort(orderField).order(SortOrder.DESC));
        }
        try {
            SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            return handleResponse(pageResult, search);
        } catch (IOException e) {
            log.error("es:list error", e);
        }
        return pageResult;
    }

    @Override
    public PageResult<T> getListByIds(String... ids) {
        if (null == ids || ids.length == 0) {
            return new PageResult<>();
        }
        SearchRequest request = new SearchRequest(this.getIndexName());
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.filter(QueryBuilders.idsQuery().addIds(ids));
        request.source().query(boolQuery);
        try {
            SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            return handleResponse(search);
        } catch (IOException e) {
            log.error("es:list error", e);
        }
        return new PageResult<>();
    }


    @Override
    public DeleteResponse deleteById(String id) {
        DeleteRequest request = new DeleteRequest(this.getIndexName(), id);
        // 2.发送请求
        try {
           return restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public BulkByScrollResponse deleteByQuery(QueryBuilder queryBuilder) {
        DeleteByQueryRequest request = new DeleteByQueryRequest(this.getIndexName());
        request.setQuery(queryBuilder);
        // 2.发送请求
        try {
            return restHighLevelClient.deleteByQuery(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 处理分页结果
     *
     * @param pageResult
     * @param response
     * @return
     */
    protected PageResult<T> handleResponse(PageResult<T> pageResult, SearchResponse response) {
        SearchHits searchHits = response.getHits();
        long total = searchHits.getTotalHits().value;
        SearchHit[] hits = searchHits.getHits();
        List<T> list = new ArrayList<>(hits.length);
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            list.add(JSON.parseObject(json, this.getTypeClass()));
        }
        pageResult.setTotal(total);
        pageResult.setList(list);
        pageResult.setQueryCondition(null);
        return pageResult;
    }

    protected PageResult<T> handleResponse(SearchResponse response) {
        return this.handleResponse(new PageResult<>(), response);
    }

    /**
     * 过滤条件
     *
     * @param params
     * @param request
     */
    protected void buildQuery(T params, SearchRequest request) {
        String[] filterQuery = getFilterQuery();
        if (null != params) {
            // 1.准备Boolean查询
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            Map<String, String> map = params.toMap();
            for (String key : filterQuery) {
                String value = map.get(key);
                if (key != null && value != null) {
                    boolQuery.filter(QueryBuilders.termQuery(key, value));
                }
            }
            QueryBuilder queryBuilder = getQueryBuilder(params);
            if (null != queryBuilder) {
                boolQuery.filter(queryBuilder);
            }
            // 3.设置查询条件
            request.source().query(boolQuery);
        }
    }

    protected abstract String[] getFilterQuery();


}

在这里插入图片描述

这个里面涉及到返回结果json字符串转对象,然后需要对象的获取对应class,而我们这里的对象又是一个泛型,无法直接获取其class.下面的获取泛型对象的class的方法

    @SuppressWarnings("unchecked")
    public Class<T> getTypeClass() {
        Type type = getClass().getGenericSuperclass();
        if (!(type instanceof ParameterizedType)) {
            throw new IllegalStateException("Type must be a parameterized type");
        }
        ParameterizedType parameterizedType = (ParameterizedType) type;
        // 获取泛型的具体类型  这里是单泛型
        Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
        if (null == actualTypeArguments || actualTypeArguments.length < 1) {
            throw new IllegalStateException("Number of type arguments must be 1");
        }
        return (Class<T>) actualTypeArguments[0];
    }
文章来源:https://blog.csdn.net/qq_39017153/article/details/134923316
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。