问题
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