Determine if a lambda expression is stateless or stateful in Java

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

    Well, a lambda expression is just an instance of a special anonymous class that only has one method. Anonymous classes can "capture" variables that are in the surrounding scope. If your definition of a stateful class is one that carries mutable stuff in its fields (otherwise it's pretty much just a constant), then you're in luck, because that's how capture seems to be implemented. Here is a little experiment :

    import java.lang.reflect.Field;
    import java.util.function.Function;
    
    public class Test {
        public static void main(String[] args) {
            final StringBuilder captured = new StringBuilder("foo");
            final String inlined = "bar";
            Function lambda = x -> {
                captured.append(x);
                captured.append(inlined);
    
                return captured.toString();
            };
    
            for (Field field : lambda.getClass().getDeclaredFields())
                System.out.println(field);
        }
    }
    

    The output looks something like this :

    private final java.lang.StringBuilder Test$$Lambda$1/424058530.arg$1
    

    The StringBuilder reference got turned into a field of the anonymous lambda class (and the final String inlined constant was inlined for efficiency, but that's beside the point). So this function should do in most cases :

    public static boolean hasState(Function lambda) {
        return lambda.getClass().getDeclaredFields().length > 0;
    }
    

    EDIT : as pointed out by @Federico this is implementation-specific behavior and might not work on some exotic environments or future versions of the Oracle / OpenJDK JVM.

提交回复
热议问题