首页 > 解决方案 > 如何序列化一个可以作为自己类型参数的泛型类?

问题描述

编辑 2:问题已解决。支持 Joachim Sauer 和 Viral Lalakia 的答案。

解决方案:Comparable<T>如果我将和交换Serializable为 type , SonarLint 不会发出警告T。它给出的警告应被视为误报。


初始问题:

所以,我有一个Pair<T>我想成为的通用类,Serializable并且Comparable. 此外,我 T成为Comparable(而且我也需要它是SerializablePair<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) 
    }

}

我在firstandlast字段上有 SonarLint 严重警告,因为它们不可序列化,即使我将它们标记为可序列化('“可序列化”类中的字段应该是瞬态的或可序列化的')

我能做些什么来解决这个问题(如果可能的话)?

(编辑1:错字)

标签: javagenericsserializationsonarlintsonarlint-eclipse

解决方案


私有静态最终长序列版本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) 
}

}


推荐阅读