SonarLint V3: Fields in a quot;Serializablequot; class should either be transient or serializable for List interface(SonarLint V3:“Serializable中的字段;对于 List 接口,类应该是瞬态的或可序列化的)
问题描述
我的问题与 this 非常相似 除了我在 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;
    }
}
现在,如果我将 List 替换为 ArrayList ,那么 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 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 是对的.问题是不能保证 elements 字段是可序列化的.您需要像这样在 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 中的标准集合类型也是如此),则列表将是可序列化的.
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:“Serializable"中的字段;对于 List 接口,类应该是瞬态的或可序列化的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SonarLint V3:“Serializable"中的字段;对于 List 接口,类应该是瞬态的或可序列化的
				
        
 
            
        - Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
 - Eclipse 插件更新错误日志在哪里? 2022-01-01
 - value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
 - 如何使用WebFilter实现授权头检查 2022-01-01
 - 从 finally 块返回时 Java 的奇怪行为 2022-01-01
 - Java包名称中单词分隔符的约定是什么? 2022-01-01
 - Jersey REST 客户端:发布多部分数据 2022-01-01
 - 将log4j 1.2配置转换为log4j 2配置 2022-01-01
 - C++ 和 Java 进程之间的共享内存 2022-01-01
 - Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
 
						
						
						
						
						