Fields in a "Serializable" class should either be transient or serializable

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xinglu31/article/details/80485216

Fields in a Serializable class must themselves be either Serializable or transient even if the class is never explicitly serialized or deserialized. That's because under load, most J2EE application frameworks flush objects to disk, and an allegedly Serializable object with non-transient, non-serializable data members could cause program crashes, and open the door to attackers.

This rule raises an issue on non-Serializable fields, and on collection fields when they are not private (because they could be assigned non-Serializable values externally), and when they are assigned non-Serializable types within the class.

Noncompliant Code Example

复制代码
public class Address {
  //...
}

public class Person implements Serializable {
  private static final long serialVersionUID = 1905122041950251207L;

  private String name;
  private Address address;  // Noncompliant; Address isn't serializable
}
复制代码

Exceptions

The alternative to making all members serializable or transient is to implement special methods which take on the responsibility of properly serializing and de-serializing the object. This rule ignores classes which implement the following methods:

 private void writeObject(java.io.ObjectOutputStream out)
     throws IOException
 private void readObject(java.io.ObjectInputStream in)
     throws IOException, ClassNotFoundException;


解决办法:

添加transient关键字,例如

public class Person implements Serializable {
  private static final long serialVersionUID = 1905122041950251207L;

  private String name;
  private transient Address address;
}

这样SonarLint的警告就会消失,可以解决该问题。



参考链接:

(0):https://blog.csdn.net/rosyhuan/article/details/78211873

(1):https://stackoverflow.com/questions/910374/why-does-java-have-transient-fields?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

(2):https://help.semmle.com/wiki/display/JAVA/Transient+field+in+non-serializable+class

(3):https://howtodoinjava.com/core-java/basics/transient-keyword-in-java-with-real-time-example/

(4):https://stackoverflow.com/questions/32651493/sonarqube-rule-fields-in-a-serializable-class-should-either-be-transient-or

(5):https://stackoverflow.com/questions/36017994/sonarqube-make-field-transient-or-serializable







没有更多推荐了,返回首页