【已解决 Flink Java API问题】The return type of function ‘xxx‘ could not be determined automatically

Flink Java API不像Scala API可以随便写lambda表达式,写完以后需要使用returns方法显式指定返回值类型,否则会报下面错误,大概意思就是说Java的lambda表达式不能提供足够的类型信息,需要指定返回值类型。不推荐使用lambda表达式而是使用匿名类。

log4j:WARN No appenders could be found for logger (org.apache.flink.api.java.ClosureCleaner).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception in thread "main" org.apache.flink.api.common.functions.InvalidTypesException: The return type of function 'main(WindowDemo.java:19)' could not be determined automatically, due to type erasure. You can give type information hints by using the returns(...) method on the result of the transformation call, or by letting your function implement the 'ResultTypeQueryable' interface.
	at org.apache.flink.api.dag.Transformation.getOutputType(Transformation.java:451)
	at org.apache.flink.streaming.api.datastream.DataStream.addSink(DataStream.java:1289)
	at org.apache.flink.streaming.api.datastream.DataStream.print(DataStream.java:971)
	at it.kenn.window.WindowDemo.main(WindowDemo.java:23)
Caused by: org.apache.flink.api.common.functions.InvalidTypesException: The generic type parameters of 'Tuple3' are missing. In many cases lambda methods don't provide enough information for automatic type extraction when Java generics are involved. An easy workaround is to use an (anonymous) class instead that implements the 'org.apache.flink.api.common.functions.MapFunction' interface. Otherwise the type has to be specified explicitly using type information.
	at org.apache.flink.api.java.typeutils.TypeExtractionUtils.validateLambdaType(TypeExtractionUtils.java:350)
	at org.apache.flink.api.java.typeutils.TypeExtractor.getUnaryOperatorReturnType(TypeExtractor.java:579)
	at org.apache.flink.api.java.typeutils.TypeExtractor.getMapReturnTypes(TypeExtractor.java:175)
	at org.apache.flink.streaming.api.datastream.DataStream.map(DataStream.java:599)
	at it.kenn.window.WindowDemo.main(WindowDemo.java:19)

Process finished with exit code 1

解决方法就是显式指定返回值即可,如下

public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStream> readyStream = env.socketTextStream("localhost", 9999)
                .map(event -> {
                    String[] strings = event.split(",");
                    return new Tuple3<>(strings[0], Long.parseLong(strings[1]), Double.parseDouble(strings[2]));
                })
                //这里指定返回值类型
                .returns(TypeInformation.of(new TypeHint>(){}));
        readyStream.print();
        
        env.execute();
    }

 

你可能感兴趣的:(Flink,flink)