Lambda表达式捕获与非捕获

2018-01-18  本文已影响46人  骊骅

问题起源

下面的相似代码执行过程中,有些会报错,有些真确,想搞懂原因

/**
 * @author haicheng.lhc@alibaba-inc.com 2018/01/18
 * @date 2018/01/18
 */

@FunctionalInterface
public interface ConsumerSerialized<T>  extends Serializable {

    void apply(T t);

}

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.util.function.BinaryOperator;

/**
 * @author haicheng.lhc@alibaba-inc.com 2018/01/18
 * @date 2018/01/18
 */

public class Test2 {

    public static void main(String[] args) throws IOException {
       
        ConsumerSerialized<String> consumer1  = s -> System.out.println(s);
        ConsumerSerialized<String> consumer2  = System.out::println;
        PrintStream printStream = System.out;
        ConsumerSerialized<String> consumer3  = s -> printStream.println(s);
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("/Users/----/object.txt"));
        out.writeObject(consumer1);//OK
        out.writeObject(consumer2);//Error
        out.writeObject(consumer3);//Error
    }
}

两种出错的异常如下

Exception in thread "main" java.io.NotSerializableException: java.io.PrintStream
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
    at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1378)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
    at com.alibaba.engine.core.Test2.main(Test2.java:42)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

问题原因

是否可序列化的问题

java.io.PrintStream是不可以序列化的。

Lambda表达式捕获与非捕获

关于Lambda表达式的 Lambda Expressions and Variable Scope可以参考文章http://www.informit.com/articles/article.aspx?p=2303960&seqNum=7

简单举例

public static void repeatMessage(String text, int count) {
    Runnable r = () -> {
        for (int i = 0; i < count; i++) {
            System.out.println(text);
        }
    };
    new Thread(r).start();
}

To understand what is happening, we need to refine our understanding of a lambda expression. A lambda expression has three ingredients:

  • A block of code
  • Parameters
  • Values for the free variables—that is, the variables that are not parameters > and not defined inside the code

In our example, the lambda expression has two free variables, text and count. The data structure representing the lambda expression must store the values for these variables—in our case, "Hello" and 1000. We say that these values have been captured by the lambda expression. (It’s an implementation detail how that is done. For example, one can translate a lambda expression into an object with a single method, so that the values of the free variables are copied into instance variables of that object.)

回到开篇的问题,在我们定义的三个consumer里面,分别讲述一下

 ConsumerSerialized<String> consumer1  = s -> System.out.println(s);

这里面没有 free variables, 所以不存在捕获的问题。

ConsumerSerialized<String> consumer2  = System.out::println;

System.out::println 这是一个实例方法的 method reference, 不但会指定要调用的方式是哪个(java.io.PrintStream.println),还会捕获这个被调用的实例(由System.out静态变量所引用的实例)

PrintStream printStream = System.out;
ConsumerSerialized<String> consumer3  = s -> printStream.println(s);

很显然,这是一个带有自由变量printStream的Lambda表达式。

上一篇下一篇

猜你喜欢

热点阅读