无法序列化我的 class 对象

Cannot Serialize my class object

我正在使用 2 classes RSAKeyPack.java 和 SerialVersionUIDTest.java

我的问题是我无法序列化 RSAKeyPack 的对象。

堆栈跟踪:

java.io.NotSerializableException: java.security.KeyPairGenerator$Delegate
 at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
 at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
 at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
 at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
 at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
 at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
 at FADE.SerialVersionUIDTest.main(SerialVersionUIDTest.java:43)
public class RSAKeyPack implements Serializable { //Object to be serialized

    private static final long serialVersionUID = 2L;
    PublicKey publicKey;
    PrivateKey privateKey;
    KeyPairGenerator keyPairGenerator;
    public RSAKeyPack()
    {
        try 
        {
            keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048); //1024 used for normal securities
            KeyPair keyPair = keyPairGenerator.generateKeyPair();  
            publicKey = keyPair.getPublic();  
            privateKey = keyPair.getPrivate();          
        } 
        catch (NoSuchAlgorithmException e) 
        {
            e.printStackTrace();
        }
    }
}

是KeyPairGenerator的问题吗? 是摘要吗class?

keyPairGenerator 可能无法序列化。

创建该字段 transient,然后为其添加惰性初始化器 getter。

或者完全删除它并在需要时直接使用 KeyPairGenerator.getInstance("RSA")

transient KeyPairGenerator keyPairGenerator;

private KeyPairGenerator getGenerator() {
   if (keyPairGenerator == null) {
       keyPairGenerator = KeyPairGenerator.getInstance("RSA");
       keyPairGenerator.initialize(2048); //1024 used for normal securities
       ...
   }
   return keyPairGenerator;
}