微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。