创建变量arity方法

时间:2017-06-07 21:47:33

标签: java arity

尝试编写一个变量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)

1 个答案:

答案 0 :(得分:0)

让我们看一下错误信息:

  

[LMember;无法投放到Member

[LMember;是数组类型(as described here),Member[]的编码名称。所以它告诉你,你正在向Member[]投射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);
    }
}

据推测,你要么需要遍历varargs并单独写每个:

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

或者您需要以数组形式读取对象:

Member[] members = (Member[]) input.readObject();