I am aware that we can cast a function to be Serializable
where we need this.
However, I would like to move this casting to a generic method, to make the using code less cluttered. I do not manage to create such a method.
My specific problem is that the below map is not Serializable
:
final Map<MyObject, String> map =
new TreeMap<>(Comparator.comparing(MyObject::getCode));
I can fix this by using:
final Map<MyObject, String> map =
new TreeMap<>(Comparator.comparing((Function<MyObject, String> & Serializable) MyObject::getCode));
But I would like to be able to do something like:
final Map<MyObject, String> map =
new TreeMap<>(Comparator.comparing(makeSerializable(MyObject::getCode)));
public static <T, U> Function<T, U> makeSerializable(Function<T, U> function) {
return (Function<T, U> & Serializable) function;
}
For the compiler this is fine, but at runtime, I get a ClassCastException
:
java.lang.ClassCastException: SerializableTest$$Lambda$1/801197928 cannot be cast to java.io.Serializable
I also tried the following alternatives, without success:
// ClassCastException
public static <T extends Serializable, U extends Serializable> Function<T, U> makeSerializable(Function<T, U> function) {
return (Function<T, U> & Serializable) function;
}
// No ClassCastException, but NotSerializableException upon Serializing
public static <T, U> Function<T, U> makeSerializable2(Function<T, U> function) {
return (Function<T, U> & Serializable) t -> function.apply(t);
}
Is it possible to create such a method?
Implementation of MyObject
:
static class MyObject implements Serializable {
private final String code;
MyObject(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}