Matan Perelmuter
01/12/2024, 11:45 PMmap 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
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("");
}Constantine
01/13/2024, 12:49 AMConstantine
01/13/2024, 12:50 AMMatan Perelmuter
01/13/2024, 12:53 AMConstantine
01/13/2024, 12:53 AMMatan Perelmuter
01/13/2024, 12:54 AMpublic 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;
}
}Constantine
01/13/2024, 12:57 AMConstantine
01/13/2024, 1:01 AMjava
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
xml
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>Constantine
01/13/2024, 1:01 AMMatan Perelmuter
01/13/2024, 12:04 PMMain::toJson causes this exception