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).
相关文章