java 使“类”成为瞬态或可序列化但该类是可序列化的
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29507980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make "class" transient or serializable BUT the class is serializable
提问by georges goebel
SonarQube 5.1 marks a lot of critical issues after reviewing my code. However the class itself and the referenced class in the field is also serializable. The referenced class inherits the serializable interface through a class.
在查看我的代码后,SonarQube 5.1 标记了很多关键问题。然而,类本身和字段中引用的类也是可序列化的。被引用的类通过一个类继承了可序列化的接口。
Here is my example
这是我的例子
public class A implements Serializable {
private B b; // -> Sonarcube markes this field as not serialzable
}
And the class B is defined as follows
B类定义如下
public class B extends C {
....
}
And the class C is defined as follows
而C类定义如下
public abstract class C extends D {
....
}
And the class D is defined
并且定义了 D 类
public abstract class D implements Serializable {
....
}
Running FindBugs on the same project does not see these problems. I am not sure if it is a bug in sonarcube or is my code has some other problems (other fields in the classes C,D or something else)
在同一个项目上运行 FindBugs 不会看到这些问题。我不确定这是 sonarcube 中的错误还是我的代码有其他问题(C、D 类中的其他字段或其他内容)
Does anybody has a clue ?
有人有线索吗?
回答by Mustafa
It is probably because the binary files are not provided correctly. I had a similar issue with my SonarQube configuration, then I discovered that the classes that implement Serializable
are in different modules and/or in an external library.
可能是因为未正确提供二进制文件。我的 SonarQube 配置也有类似的问题,然后我发现实现的类Serializable
位于不同的模块和/或外部库中。
Setting correct values for sonar.java.binaries
and sonar.java.libraries
allow SonarQube to locate the binaries and correctly determine whether or not the classes are serializable.
设置正确的值sonar.java.binaries
并sonar.java.libraries
允许 SonarQube 定位二进制文件并正确确定类是否可序列化。
回答by SpaceTrucker
Just because some base class is implementing Serializable
does not mean that automatically all derived classes are correctly serializable. Derived classes should define there own serialVersionUid
. Also derived classes could introduce new field whose values might not be serializable.
仅仅因为某些基类正在实现Serializable
并不意味着所有派生类都可以自动正确序列化。派生类应该在那里定义自己的serialVersionUid
. 派生类也可以引入其值可能不可序列化的新字段。
So unless SonarQube has a hint that the author actually meant the class to be serializable (possibly by restating implements Serializable
or by declaring serialVersionUid
) it is correct for SonarQube to be suspicios about it by Liskovs substition principle.
因此,除非 SonarQube 暗示作者实际上意味着该类是可序列化的(可能通过重述implements Serializable
或声明serialVersionUid
),否则 SonarQube 对 Liskovs 替换原则的怀疑是正确的。
However the classification as critical could be something that needs discussion. But that is too opinion based for here.
然而,关键的分类可能需要讨论。但这太基于意见了。