Hey, when using method reference in `map` function...
# troubleshooting
m
Hey, when using method reference in
map
function I get class cast exception. changing the method reference to regular lambda fix the issue, but I'd like to hear if someone knows why this happens
Copy code
public static void main(String[] args) throws Exception {
    final StreamExecutionEnvironment env =  StreamExecutionEnvironment.getExecutionEnvironment();
    env.setRuntimeMode(RuntimeExecutionMode.STREAMING);

    DataStream<Foo> foo = env.fromElements(new Foo("2"));
    DataStream<Bar> bar = env.fromElements(new Bar("1"));

    KafkaSink<String> sink = getKafkaSink();
    // Fails with: Caused by: java.lang.ClassCastException: class org.matan.Main2$Bar cannot be cast to class org.matan.Main2$Foo (org.matan.Main2$Bar and org.matan.Main2$Foo are in unnamed module of loader org.apache.flink.util.ChildFirstClassLoader @272d4f9b)
    foo.map(Main::toJson).sinkTo(sink);
    bar.map(Main::toJson).sinkTo(sink);
    // Works:
    foo.map(v -> Main.toJson(v)).sinkTo(sink);
    bar.map(v -> Main.toJson(v)).sinkTo(sink);

    env.execute("");
}
c
Are Foo and Bar data classes?
Look like those aren't actually types, but rather variables
m
Yes, they are classes, I didn't add their definition
c
May I see the definitions?
m
sure
Copy code
public class Bar {
    public String id;

    public Bar(String id) {
        this.id = id;
    }
}

public class Foo {
    public String id;

    public Foo(String id) {
        this.id = id;
    }
}
c
I think u just need to add to and from json methods
Copy code
java
import com.google.gson.Gson;

public class Bar {
    public String id;

    public Bar(String id) {
        this.id = id;
    }

    //to json 
    public String toJSON() {
        Gson gson = new Gson();
        return gson.toJson(this);
    }

    // from Json
    public static Bar fromJSON(String json) {
        Gson gson = new Gson();
        return gson.fromJson(json, Bar.class);
    }

    // toMap
    public Foo mapToFoo() {
        return new Foo(this.id);
    }
}

public class Foo {
    public String id;

    public Foo(String id) {
        this.id = id;
    }

    // to JSON
    public String toJSON() {
        Gson gson = new Gson();
        return gson.toJson(this);
    }

    // from JSON
    public static Foo fromJSON(String json) {
        Gson gson = new Gson();
        return gson.fromJson(json, Foo.class);
    }

    // to map
    public Bar mapToBar() {
        return new Bar(this.id);
    }
}
Add this to ur pom.xml
Copy code
xml
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.9</version>
</dependency>
Should look something like this
m
I already found a fix, the question is why using
Main::toJson
causes this exception