为什么将新的Greeting()作为Greeting是lambdas表达式中的接口?

时间:2018-10-09 14:17:08

标签: java lambda

Greeter.java

# Datalab might need an older version of pip
# !pip install pip==9.0.3

import apache_beam as beam
from apache_beam.options.pipeline_options import GoogleCloudOptions
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import StandardOptions

project_id = 'my-project'
bigquery_dataset_name = 'testdataset' # needs to exist 
table_name = 'testtable'
bucket_name = 'my-bucket'
json_file_gcs_path = 'gs://path/to/my/file.json'
schema = "name:STRING,zipcode:STRING"

def json_processor(row):
    import json
    d = json.loads(row)
    return {'name': d['name'], 'zipcode': d['zipcode']}

options = beam.options.pipeline_options.PipelineOptions()
google_cloud_options = options.view_as(GoogleCloudOptions)
google_cloud_options.project = project_id
google_cloud_options.job_name = "myjob"
google_cloud_options.staging_location = 'gs://{}/binaries'.format(bucket_name)
google_cloud_options.temp_location = 'gs://{}/temp'.format(bucket_name)
options.view_as(StandardOptions).runner = 'DataflowRunner'
google_cloud_options.region = "europe-west1"

p = beam.Pipeline(options=options)

(p | "read_from_gcs" >> beam.io.ReadFromText(json_file_gcs_path)
   | "json_processor" >> beam.Map(json_processor)
   | "write_to_bq" >> beam.io.Write(beam.io.gcp.bigquery.BigQuerySink(table=table_name, 
                                                       dataset=bigquery_dataset_name, 
                                                       project=project_id, 
                                                       schema=schema, 
                                                       create_disposition='CREATE_IF_NEEDED',
                                                       write_disposition='WRITE_EMPTY'))
)

p.run()

Greeting.java

package lambda;
import java.util.stream.*;

public class Greeter {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Greeting Greet1 = () -> System.out.println("Hello gretting..");

        Greeting innerclass = new Greeting() {
            //why new Greeting is an interface ?
            public void perform(){
                System.out.println("Hello inner greeting");
            }
        };
        Greet1.perform();
        innerclass.perform();
    }
}
  

输出

你好,gretting ..

你好内在问候语...

为什么这行有效?

package lambda;

public interface Greeting {

    public void perform();

}

1 个答案:

答案 0 :(得分:0)

因为Greeting innerclass = new Greeting() ...创建了一个实现Greeting接口的匿名内部类

看看https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html