-2

尝试编写一个变量arity方法serializeMethod(),它将任意数量的Member实例作为参数,并按照它们传递给方法的顺序将它们写入文件。该文件是隐藏的,而是通过将放置方法的类中的 ostream 实例变量引用的 OutputStream 对象提供给您。有问题不知道为什么它不接受会员

public void serializeMethod(Member... member) {
    ObjectOutputStream output = null;
    try {
        output = new ObjectOutputStream(ostream);
        output.writeObject(member);
        output.close();
    }catch(IOException e) {
        System.out.print("IOException :" + e);
    }

}


Test case:
Member m1 = new Member("SI2993", 'c', 2);
Member m2 = new Member("GE8103", 's', 1);
Member m3 = new Member("PD9320", 's', 1);
Member m4 = new Member("NE9025", 'c', 4);
Member m5 = new Member("QW3234", 's', 1);
serializeMethod(m1, m2, m3, m4, m5);
deSerializeMethod();

Expected result :

Member ID: SI2993
Member role: c
Length of membership: 2
Member ID: GE8103
Member role: s
Length of membership: 1
Member ID: PD9320
Member role: s
Length of membership: 1
Member ID: NE9025
Member role: c
Length of membership: 4
Member ID: QW3234
Member role: s
Length of membership: 1

My output:
Exception in thread "main" java.lang.ClassCastException: [LMember; cannot be cast to Member
\x09at SerializeMethodVariableArity.deSerializeMethod(SerializeMethodVariableArity.java:144)
\x09at SerializeMethodVariableArity.runTests(SerializeMethodVariableArity.java:188)
\x09at SerializeMethodVariableArity.main(SerializeMethodVariableArity.java:178)
4

1 回答 1

0

我们来看看错误信息:

[LMember;不能转换为Member

[LMember;是数组类型的编码名称(如此处所述Member[],. 所以它告诉你你正在铸造一个Member[]to Member

大概在deSerializeMethod你有一些这样的代码:

Member m = (Member) input.readObject();

但是在您的 中serializeMethod,您正在编写一个数组:

public void serializeMethod(Member... member) {
    ObjectOutputStream output = null;
    try {
        output = new ObjectOutputStream(ostream);
        output.writeObject(member);
        //                 ^^^^^^
        // member is an array, because varargs are
        // syntactic sugar for passing an array
        output.close();
    }catch(IOException e) {
        System.out.print("IOException :" + e);
    }
}

大概您需要遍历可变参数并分别编写每个参数:

for (Member m : members) {
    output.writeObject(m);
}

或者您需要将对象作为数组读取:

Member[] members = (Member[]) input.readObject();
于 2017-06-07T21:56:45.937 回答