简体   繁体   中英

Can you program Java collections to an interface and use Serializable?

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?

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 Integer s), then the object will serialize.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM