Determine if a lambda expression is stateless or stateful in Java

后端 未结 4 931
南旧
南旧 2021-02-01 20:01

Is there a function which accepts a reference to a lambda expression and returns a boolean saying whether the lambda expression is stateless or not? How can the statefulness of

4条回答
  •  长发绾君心
    2021-02-01 20:14

    Here's a simple and stupid idea. Just check if your lambda has fields.

    For instance, consider the following stateful lambda.

      List serialStorage = new ArrayList<>();
      Function statefulLambda =
          e -> { serialStorage.add(e); return e; };
    

    This statefulLambda has a private final internal field arg$1 which obviously references serialStorage. So

      statefulLambda.getClass().getDeclaredFields().length > 0
    

    could be used as indicator that lambda is stateful.

    However I have no idea if this will generally work.

提交回复
热议问题