get Serialized Lambda using reflection - Java Lambda Stream

Java examples for Lambda Stream:Function

Description

get Serialized Lambda using reflection

Demo Code


import java.lang.invoke.SerializedLambda;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Optional;
import java.util.function.Function;

public class Main{
    public static Optional<SerializedLambda> getSerializedLambda(
            SerializableFunction lambda) {
        Method writeReplace = null;
        SerializedLambda sl = null;
        try {//from   ww  w  .  j a va  2 s.  c om
            writeReplace = lambda.getClass().getDeclaredMethod(
                    "writeReplace");
            writeReplace.setAccessible(true);
            sl = (SerializedLambda) writeReplace.invoke(lambda);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } finally {
            return Optional.of(sl);
        }
    }
}

Related Tutorials