Is Key1List Serializable

17 views
Skip to first unread message

Peter Pfort

unread,
Oct 20, 2015, 8:52:06 AM10/20/15
to brownies-collections
Hello,

I have a problem to serialize my class, that use a Key1List.

I think, Key1List isn't Serializable, because there is now public constructor.

Is this right?

Regards

Peter

Thomas Mauch

unread,
Oct 20, 2015, 5:43:35 PM10/20/15
to brownies-collections
Hi Peter

Key1List is serializable. There are some technologies around like JAXB or JPA that need a default constructor, but Java serialization does not.
I guess that the problem you encounter comes from serializing the mapping function of the Key1List.
Unfortunately it is quite tricky to get a serializable mapping function - even with Java 8 lambdas.

So the simplest approach using lambda will not work, because lambdas are per default not serializable:
list = new Key1List.Builder<Name,String>().withKey1Map(Name::getName).build(); // not serializable

To make it serializable, you have to explicitly cast the lambda using type intersection:
list = new Key1List.Builder<Name,String>().withKey1Map((IFunction<Name,String> & Serializable) Name::getName).build(); // serializable

The situation is similar if you don't user Java 8: the straightforward approach is not serializable:
        list = new Key1List.Builder<Name,String>().
            withKey1Map(new IFunction<Name,String>() {
                @Override
                public String apply(Name name) {
                    return name.toString();
                }
            }).build(); // not serializable

As you cannot apply type intersection to anonymous classes, you have to explicitly define a class to make it work:
        class NameMapper implements IFunction<Name,String>, Serializable {
            public String apply(Name name) {
                return name.toString();
            }
        };
        list = new Key1List.Builder<Name,String>().withKey1Map(new NameMapper()).build(); // serializable

I hope that helps.
Otherwise please post a short example with a description of the problems you encounter.

Regards,
Thomas

Peter Pfort

unread,
Oct 21, 2015, 3:44:21 AM10/21/15
to brownies-collections
Hi Thomas,

yes, it's serializable.

The problem was an anonymous class as you describe.

Thank you,

Peter
Reply all
Reply to author
Forward
0 new messages