code: public static SerializedLambda getSerializedLambda(Object lambda) {
          Objects.requireNonNull(lambda);
          
          if (!(lambda instanceof java.io.Serializable)) {
              throw new IllegalArgumentException("Functional object does not implement java.io.Serializable");
          }
  
          for (Class<?> clazz = lambda.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
              try {
                  Method replaceMethod = clazz.getDeclaredMethod("writeReplace");
                  replaceMethod.setAccessible(true);
                  Object serializedForm = replaceMethod.invoke(lambda);
  
                  if (serializedForm instanceof SerializedLambda) {
                      return (SerializedLambda) serializedForm;
                  }
              } catch (NoSuchMethodError e) {
                  // fall through the loop and try the next class
              } catch (NoSuchMethodException e) {
                  throw new IllegalArgumentException("Functional object is not a lambda");
              } catch (SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                  throw new RuntimeException("Unable to cleanly serialize lambda", e);
              }
          }
  
          throw new RuntimeException("writeReplace method not found");
      }
docs: Tries to get a SerializedLambda from an Object by searching the class
  hierarchy for a <code>writeReplace</code> method.  The lambda must
  be serializable in order for this method to return a value.
  @param lambda An object that is an instance of a functional interface.
  @return The SerializedLambda