Is a reference to an instance method serialized in Java 8?

I want to know if a reference to an instance method of an arbitrary object of a certain type is serializable or not?

Example:

public class MyClass {
    public void foo() {
        System.out.println("Serializable");
    }
}

SerializableConsumer

@FunctionalInterface
public interface SerializableConsumer<T> extends Consumer<T>, Serializable {
}

and field:

SerializableConsumer<MyClass> serializableMethod = MyClass::foo;

EDITED

+6
source share
2 answers

Assuming that it SerializableFunctionis of a type that extends Serializable, the method reference will be serialized. There is nothing special about the particular type of method reference you are asking for.

, " " - MyClass, , MyClass isnt Serializable . , object::foo, , , Serializable.

, void Function void. , SerializableFunction<MyClass, Void>, Function<MyClass, Void>&Serializable, .

, :

import java.io.*;
import java.util.function.Consumer;

public class MyClass {
    public void foo() {
        System.out.println("Serializable");
    }
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Consumer<MyClass> consumer = (Consumer<MyClass>&Serializable)MyClass::foo;

        byte[] serialized;
        try(ByteArrayOutputStream baos=new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos)) {
            oos.writeObject(consumer);
            oos.flush();
            serialized=baos.toByteArray();
        }

        Consumer<MyClass> deserialized;
        try(ByteArrayInputStream bais=new ByteArrayInputStream(serialized);
            ObjectInputStream ois=new ObjectInputStream(bais)) {
            deserialized = (Consumer<MyClass>)ois.readObject();
        }

        deserialized.accept(new MyClass());
    }
}

, , , ,

import java.io.*;
import java.util.function.Consumer;

public class MyClass {
    public void foo() {
        System.out.println("Serializable");
    }
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Runnable runnable = (Runnable&Serializable)new MyClass()::foo;

        byte[] serialized;
        try(ByteArrayOutputStream baos=new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos)) {
            oos.writeObject(runnable);
            oos.flush();
            serialized=baos.toByteArray();
        }

        Runnable deserialized;
        try(ByteArrayInputStream bais=new ByteArrayInputStream(serialized);
            ObjectInputStream ois=new ObjectInputStream(bais)) {
            deserialized = (Runnable)ois.readObject();
        }

        deserialized.run();
    }
}

java.io.NotSerializableException: MyClass, MyClass Serializable.

+5

, lambda expresion ( )

, , ? ?... , , . , , , , :

Runnable r = (Runnable & Serializable)() -> System.out.println("Serializable!");
0

Source: https://habr.com/ru/post/1017020/


All Articles