Java Serializable and lambda expressions

239 views Asked by At

I need to save an object on file, then retrieve it later. The object itself implements the interface Serializable, but one of its fields contains lambda expressions. Apparently this counts as a field that does not implements the Serializable interface and I get a java.io.NotSerializableException.

I do not want to drastically change my code, but I do not know what to do in such a situation. Someone has a suggestion?

Here is a sample code that replicates this problem:

public class SerObject implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = -2691834780794406081L;

public SerField field;

public SerObject(SerField field) {
    this.field = field;
}

public String stringRepresentation() {
    return this.field.name() + "\t" + field.lambda.apply(field);
}

static final String pathname = "D:\\JavaData\\file.obj";

public static void main(String[] args) {
    SerObject obj = new SerObject(new SerField("Field", (field) -> "Class is " + field.getClass().getName()  ));
    
    SerializableUtilities.saveObject(new File(pathname), obj);
    
    SerObject loadedObj = SerializableUtilities.loadObject(new File(pathname));
    System.out.println(loadedObj.stringRepresentation());
}
}

public class SerField implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = -5058433150929459799L;

protected String name;

protected Function<SerField, String> lambda;

public SerField(String name, Function<SerField, String> lambda) {
    this.name = name;
    this.lambda = lambda;
}

public abstract String name() {
    return this.name;
}

}

0

There are 0 answers