views:

403

answers:

3

I've gone through and programmed all my domain level logic to interfaces. Now I find that when I want to put data in a bean, the bean doesn't work because the Collection interfaces (Collection, List, Set, etc) do not implement Serializable.

Do I need to refactor all my code to use concrete types or is there a better course of action here?

A: 

I'm not sure what you mean. I'd give some code examples of exactly what is giving you trouble.

Licky Lindsay
This might be a better comment then an answer. But essentially the Collection field in my bean is always null because it is not serializable. I was annoyed that I was going to have to refactor my code to go against Object Oriented best practices so I am looking for alternative solutions.
James McMahon
Is your issue that the Collection is unserializable, or that the objects *in* the collection are unserializable?Either way, look up the standard refactoring called "encapsulate collection".
Licky Lindsay
http://sourcemaking.com/refactoring/encapsulate-collection
Licky Lindsay
The issue is that he's trying to store a Collection in his bean (as an interface type for flexibility), but Collection does not implement Serializable so he's forced to use a concrete subtype which does.
Michael Myers
+4  A: 

If your class implements Serializable and all of its members are serializable, then the object can be serialized correctly. Example:

public class Person implements Serializable {
    private String name;
    private Collection<Integer> luckyNumbers = new ArrayList<Integer>();
}

As long as luckyNumbers's instance is serializable (such as ArrayList), and its members are serializable (in this case Integers) , then the object will serialize.

Steve Kuo
My instances are serializable, I believe. Is this true for Java 5 only?
James McMahon
Do you have a reference? Have you tested this? If so, I'll delete my answer.
Michael Myers
No, this also holds for java 1.4. If your collection is Serializable, like, for example, ArrayList, your class will serialize properly.
Jorn
Try catching NotSerializableException when you serialize, it should direct you as to what's not serializable.
Steve Kuo
Tested this and it does work, thank you.
James McMahon
A: 

Serializable is a "marker" interface. It is not suitable to be used a reference's type. Live with a bit of dynamic typing (though there is nothing to stop you using an external static type checker).

You could jump through hoops with weird parameterised generic methods, but it would be extremely ugly and the Java libraries don't do that so you'd be hosed anyway.

Tom Hawtin - tackline