java 各种深拷贝

es query拷贝

    /**
     * 深拷贝 query builder
     *
     * @param queryBuilder 原query
     * @return org.elasticsearch.index.query.QueryBuilder 返回query
     */
    public static QueryBuilder copyQueryBuilder(QueryBuilder queryBuilder) throws IOException {
        SearchModule searchModule = new SearchModule(Settings.EMPTY, false, Collections.emptyList());
        XContentParser parser = XContentFactory.xContent(XContentType.JSON).createParser(
                new NamedXContentRegistry(searchModule.getNamedXContents()), LoggingDeprecationHandler.INSTANCE, queryBuilder.toString());
        return AbstractQueryBuilder.parseInnerQueryBuilder(parser);
    }

 

深拷贝集合  需要继承序列化接口

    /**
     * 深拷贝list
     *
     * @param src list
     * @return java.util.List<T>
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> deepCopyList(List<T> src) {
        List<T> dest = Collections.emptyList();
        try {
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(byteOut);
            out.writeObject(src);
            ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
            ObjectInputStream in = new ObjectInputStream(byteIn);
            dest = (List<T>) in.readObject();
        } catch (Exception e) {
            log.error("list转化出错:", e);
            return dest;
        }
        return dest;

    }

    /**
     * 深拷贝Map
     *
     * @param src 源map
     * @return java.util.Map<K, V>
     */
    @SuppressWarnings("unchecked")
    public static <K, V> Map<K, V> deepCopyMap(Map<K, V> src) {
        Map<K, V> dest = Collections.emptyMap();
        try {
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(byteOut);
            out.writeObject(src);
            ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
            ObjectInputStream in = new ObjectInputStream(byteIn);
            dest = (Map<K, V>) in.readObject();
        } catch (Exception e) {
            log.error("map转化出错:", e);
            return dest;
        }
        return dest;

    }

 

bean 深拷贝 需要继承序列化  这个是hutool的工具

 

 ObjectUtil.cloneByStream(xxx);

 

posted @ 2022-08-05 16:01  大哥超帅  阅读(112)  评论(0编辑  收藏  举报