为什么我仍然得到类没有有效的构造函数错误

时间:2014-01-16 18:07:48

标签: java exception certificate

请问我是java编程的新手。我正在尝试将一个类写入bytearrayoutputstream,然后将这些数据传递给一个简单的数组。

然后我从字节数组中读取并重构该类。

我正在使用ObjectOutputStream和ObjectInputStream执行此操作。但我不明白为什么我仍然得到java.io.InvalidClassException:我的类没有有效的构造函数。我能找到的最好的帮助是java.io.InvalidClassException: no valid constructor

我的代码:

// this is the class I am writing to the ByteArrayOutputStream
public class CrtB extends X509v3CertificateBuilder implements Serializable {
    private static final long serialVersionUID = 1234509876;

    public CrtB(X500nEx arg0, BigInteger arg1, Date arg2, Date arg3,
            X500nEx arg4, SubjectPublicKeyInfo arg5) {
        super(arg0, arg1, arg2, arg3, arg4, arg5);
    }
}
    //this how I pass the class to the ByteArrayOutputStream and then reconstruct it

public class Testclass implements Serializable {  

    public  CrtB getCrt(){
        subpubInfo=SubjectPubInfo.getInstance(getPublicKey.getEncoded());
        certbld=new CrtB(name1, serialNr, start, end,name2, subpubInfo);
        return certbld; // certbld is a global variable
    }

    //writes to the ByteArrayOutputStream
    private  ByteArrayOutputStream writetoBAS(){
        ByteArrayOutputStream bout=null;
        try{
            bout=new ByteArrayOutputStream();
            ObjectOutputStream obj=new ObjectOutputStream(bout);
            obj.writeObject(certbld);
            obj.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        return bout;

    }
    //read from byte array
    private  CrtB getbui(byte[] ar){
    CrtB b=null;
    try {
        ByteArrayInputStream bin=new ByteArrayInputStream(ar);
        ObjectInputStream oin=new ObjectInputStream(bin);
        b=(CrtB)oin.readObject();
        System.out.println("successfully transferred");
    }catch (Exception e){
        e.printStackTrace();
    }
    return b;
    }

    public static void main(String[] args) {

        Testclass rqR=new Testclass();
        rqR.CrtB();
    byte[] br=rqR.writeBAS().toByteArray();
      CrtB b=rqR.getbui(br);
    }
}

任何人都可以帮助我或给我一个提示。

1 个答案:

答案 0 :(得分:1)

来自SerializableTo allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime.

您的情况是X509v3CertificateBuilder没有实现SerializableX509v3CertificateBuilder没有可访问(公共或受保护)的无参数构造函数。

它是否回答了您的问题“I don't understand why I am still getting java.io.InvalidClassException”?

我找到了X509v3CertificateBuilder here的定义。你使用过这个吗?