SonarLint V3: Fields in a “Serializable” class should either be transient or serializable for List interface

喜夏-厌秋 提交于 2019-12-04 03:48:27

问题


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

My code is :

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;

    }

}

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

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 ?


回答1:


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 {}

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



来源:https://stackoverflow.com/questions/45279371/sonarlint-v3-fields-in-a-serializable-class-should-either-be-transient-or-ser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!