SonarLint V3:“可序列化”字段中的字段对于List接口,class应该是瞬态的或可序列化的 [英] SonarLint V3: Fields in a "Serializable" class should either be transient or serializable for List interface

查看:4113
本文介绍了SonarLint V3:“可序列化”字段中的字段对于List接口,class应该是瞬态的或可序列化的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题非常类似于这个除了我在SonarLint V3中遇到的这个问题(squid:S1948)。

My question is very similar to this except that this issue I have encountered in SonarLint V3 (squid:S1948).

我的代码是:

public class Page<T> implements Serializable {

    Summary summary;
    List<T> elements;

    public Page() {
        summary = new Summary();
    }

    public List<T> getItemsReceived() {
        return elements;
    }

    public void setItemsReceived(List<T> list) {
        this.elements = list;
    }

    public Summary getSummary() {
        return summary;
    }

    public void setSummary(Summary summary) {
        this.summary = summary;
    }

}

摘要对象实现可序列化。

The Summary Object implements serializable.

public class Summary implements Serializable {

    int offset;
    int limit;
    long totalElements;

    public int getOffset() {
        return offset;
    }

    public void setOffset(int offset) {
        this.offset = offset;
    }

    public int getLimit() {
        return limit;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }

    public long getTotalNumberOfElements() {
        return totalElements;
    }

    public void setTotalNumberOfElements(long totalNumberOfElements) {
        this.totalElements = totalNumberOfElements;

    }

}

现在,如果我用ArrayList替换List,然后在SonarLint中出现另一个警告,我们应该使用接口而不是实现类。

Now, If I replace List by ArrayList , then another warning in SonarLint arises that we should be using interface instead of implementation classes.

我认为这可能在SonarQube中解决但是对于SonarLint I不知道。
这是一个错误还是我做错了什么?

I think this might be resolved in SonarQube but for SonarLint I don't know. Is this a bug or am I doing something wrong ?

推荐答案

SonarLint是对的。问题是无法保证元素字段是可序列化的。你需要在 T 上添加类型绑定类似这样的

SonarLint is right. The problem is that there is no guarantee that elements field is serializable. You need to add type bound on T type like this

public class Page<T extends Serializable> implements Serializable {}

这样,如果为它选择的实现是可序列化的,那么列表将是可序列化的(这是对于Java中的标准集合类型,则为true。

This way the list will be serializable if implementation chosen for it is serializable (which is true for standard collection types in Java).

这篇关于SonarLint V3:“可序列化”字段中的字段对于List接口,class应该是瞬态的或可序列化的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆