Determine if a lambda expression is stateless or stateful in Java

后端 未结 4 925
南旧
南旧 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:24

    No, it is not generally possible. The suggested approach of checking whether the lambda belongs to a class with a field is the next best thing, but having a field does not equal having a state.

    class Stateless {
        int result = 0;
        public int getResult() { return result; }
    }
    

    It is possible to prove statefulness by finding two input sequence for which a given input combination returns a different result. However, it is not possible to prove that such a input sequence does not exist (any input sequence might produce a different result if prepended by another invocation).

    (Even if you check the values of fields found via reflection, those might change without influencing the lambda's result, therefore not really making it stateful).

    Here's a short compilable example showing both false positive and negatives, disproving the notion:

    public class StatefulLambda {
        static AtomicInteger counter = new AtomicInteger();
    
        public static void main(String[] args) {
            // false negative: will return different result each call
            System.out.println(hasState(i -> counter.incrementAndGet()));
    
            // false positive: will always return the same result
            Object object = new Object() {
                final int i = 0;
            };
            System.out.println(hasState(i -> object.toString()));
        }
    
        private static boolean hasState(Function lambda) {
            return lambda.getClass().getDeclaredFields().length > 0;
        }
    }
    

提交回复
热议问题