Trying to write a variable arity method serializeMethod() that takes any number of instances of Member as parameters and write them to a file in the order they are passed into the method. The file is hidden and is instead made available to you via an OutputStream object referenced by the ostream instance variable in the class in which your method will be placed. Having problems not sure why it doesn't accept member
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)
Let's look at the error message:
[LMember;
cannot be cast toMember
[LMember;
is the encoded name of an array type (as described here), Member[]
. So it's telling you that you're casting a Member[]
to Member
.
Presumably in your deSerializeMethod
you have some code like this:
Member m = (Member) input.readObject();
But in your serializeMethod
, you're writing an array:
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);
}
}
Presumably you either need to loop over the varargs and write each one individually:
for (Member m : members) {
output.writeObject(m);
}
Or you need to read the object in as an array:
Member[] members = (Member[]) input.readObject();