This is exactly what serialization frameworks do. Of course, we can’t serialize just any object, it has to meet some requirements provided by the framework.
Going back to lambdas: technically speaking, there is no such thing as lambda. Lambdas are simply classes, only represented differently in the code. That means two things. First: yes, in many cases they can be serialized, then deserialized and even executed. Second, underneath lambda could be many much different things. We don’t really serialize/deserialize “the lambda”, but the class it represens and this class could be Function0
, it could be Function2<Int, Int, Int>
, it could be Runnable
, Callable
, Supplier
or MyCustomClass
. This is what you really serialize and if you want to be able to execute it after deserialization, then you have to think in terms of working with types mentioned above, not in terms of “lambdas”.
So the real question here is: what do you mean by “lambda”? Depending on your specific case, there could be many different answers.
edit:
Also, please be aware lambdas don’t have stable/reliable type names in the code. If you store such lambda in the DB, then to make sure you can load it back, you not only has to use the same application, but also in exactly the same version. If you save, then rebuild the application and load, then it may crash.
edit2:
I just realized you never mentioned “lambdas” - in your first post you asked about “functions” and provided an example of Function1
. If this is your case and you store Function0
, Function1
and similar objects across your application, then yes, it is potentially possible to serialize, deserialize and execute them. Although that depends on the specific implementation. Some could be serialized, others couldn’t.