如何序列化可以作为其自身类型参数的泛型类?

问题描述

编辑2:问题已解决。约阿希姆·绍尔(Joachim Sauer)和病毒拉拉基亚(Viral Lalakia)的道具。

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


初始问题:

因此,我有一个通用类Pair<T>,我想成为SerializableComparable。 此外,我想要 T成为Comparable(而我需要Serializable变成Pair<T>也可以序列化。)

PairCoord继承自其中,其中TInteger

我正在使用SonarLint进行代码分析,并且我正试图强迫自己听从每条建议(尤其是非常重要的建议),并且它一直在警告我有关通用类Pair的属性未被可序列化的东西,尽管已经将它们标记为这样。

这是我所做的:

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) 
    }

}

而且我在firstlast字段上有SonarLint严重警告,因为它们无法序列化,即使我将它们标记为可序列化(“ Serializable”类中的字段也应该是瞬态或可序列化”)

该如何解决(如果可能)?

(编辑1:错字)

解决方法

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

}

公共类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) 
}

}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...