java - 如何序列化一个可以作为自己类型参数的泛型类?
问题描述
编辑 2:问题已解决。支持 Joachim Sauer 和 Viral Lalakia 的答案。
解决方案:Comparable<T>
如果我将和交换Serializable
为 type , SonarLint 不会发出警告T
。它给出的警告应被视为误报。
初始问题:
所以,我有一个Pair<T>
我想成为的通用类,Serializable
并且Comparable
. 此外,我想 T
成为Comparable
(而且我也需要它是Serializable
可Pair<T>
序列化的)。
该类PairCoord
继承自它,并且T
是一个Integer
.
我正在使用 SonarLint 进行代码分析,我试图强迫自己遵循每一个建议(尤其是非常重要的建议),并且它一直警告我泛型 classPair
的属性不是可序列化的,尽管已将它们标记为.
这是我所做的:
public class Pair<T extends Comparable<? super T> & Serializable> implements Comparable<Pair<T>>, Serializable {
private static final long serialVersionUID = 5797102044530257848L;
private T first;
private T last;
public Pair(T first, T last) {
this.first = first;
this.last = last;
}
public Pair() {
}
// And so on
}
public class PairCoord extends Pair<Integer> implements Serializable {
private static final long serialVersionUID = 8389593640798914292L;
public PairCoord(int first, int last) {
super(first, (last + 8) % 8);
// Since each of the 3 squares are loops, the node before n°0 is therefore n°-1
// Except that n°-1 doesn't exist, but (-1 mod 8) = 7
// The only issue is that % isn't a modulo, but the remain of the euclidean division
// So by adding 8 to "last", I make sure that the number in the operation is positive,
// and since for all x >= 0, % behaves like mod, I have my node number correct (between 0 and 7)
}
}
我在first
andlast
字段上有 SonarLint 严重警告,因为它们不可序列化,即使我将它们标记为可序列化('“可序列化”类中的字段应该是瞬态的或可序列化的')
我能做些什么来解决这个问题(如果可能的话)?
(编辑1:错字)
解决方案
私有静态最终长序列版本UID = 5797102044530257848L;
private T first;
private T last;
public Pair(T first, T last) {
this.first = first;
this.last = last;
}
public Pair() {
}
// And so on
}
公共类 PairCoord 扩展 Pair 实现 Serializable {
private static final long serialVersionUID = 8389593640798914292L;
public PairCoord(int first, int last) {
super(first, (last + 8) % 8);
// Since each of the 3 squares are loops, the node before n°0 is therefore n°-1
// Except that n°-1 doesn't exist, but (-1 mod 8) = 7
// The only issue is that % isn't a modulo, but the remain of the euclidean division
// So by adding 8 to "last", I make sure that the number in the operation is positive,
// and since for all x >= 0, % behaves like mod, I have my node number correct (between 0 and 7)
}
}
推荐阅读
- oracle - PLS-00103:在预期以下情况之一时遇到符号“)”:(
- java - 如果在没有 JMSPriority 标头的情况下发送 JMS 消息会发生什么
- html - 与 NavBar 位于同一行的 FontAwesome 图标
- asp.net - 从 json 转换为 vb.net 类时对象为空
- ini - 我错过了什么,或者这是无效的吗?
- php - 将服务注入服务
- javascript - 为什么map函数返回未定义但console.log注销?
- c# - 由 R.Net 引起的 WCF 中的 StackOverflow
- java - 使用 Intent 将双精度从一个类传递到另一个类时出现 NullPointerException
- c# - 绑定文本框的可见性以查看内容模板中的模型属性