确定lambda表达式在Java中是无状态还是有状态 [英] Determine if a lambda expression is stateless or stateful in Java
问题描述
是否有一个函数接受对lambda表达式的引用并返回一个布尔值,说明lambda表达式是否为无状态?如何确定lambda表达式的有状态?
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 a lambda expression be determined?
推荐答案
嗯,lambda表达式只是一个特殊匿名类的实例只有一种方法。匿名类可以捕获周围范围内的变量。如果你对有状态类的定义是在其字段中携带可变内容的那个(否则它几乎只是一个常量),那么你很幸运,因为那是如何实现捕获。这是一个小实验:
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<String, String> lambda = x -> {
captured.append(x);
captured.append(inlined);
return captured.toString();
};
for (Field field : lambda.getClass().getDeclaredFields())
System.out.println(field);
}
}
输出如下所示:
private final java.lang.StringBuilder Test$$Lambda$1/424058530.arg$1
StringBuilder
引用变成了匿名lambda类的字段(并且最终字符串内联
常量被内联以提高效率,但这不是重点。所以这个函数在大多数情况下都应该这样做:
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;
}
编辑:正如@Federico所指出的,这是特定于实现的行为,可能不适用于某些异国情调的环境或未来版本的 Oracle / OpenJDK JVM 。
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.
这篇关于确定lambda表达式在Java中是无状态还是有状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!