简体   繁体   中英

Java - How to pass the class of a generic type into a method

The method in JavaSparkContext.newAPIHadoopRDD takes class as a parameter.

In scala I was able to use the method like so:

sc.newAPIHadoopRDD(job.getConfiguration,
      classOf[AvroKeyInputFormat[AvroFlumeEvent]],
      classOf[AvroKey[AvroFlumeEvent]],
      classOf[NullWritable])

How do i do that in java?

How do I pass the class of AvroKeyInputFormat<AvroFlumeEvent> into the method.

The closest I got was:

        Class<AvroKeyInputFormat<AvroFlumeEvent>> inputFormatClass;
        Class<AvroKey<AvroFlumeEvent>> keyClass;

        JavaPairRDD<AvroKey<AvroFlumeEvent>, NullWritable> flumeEvents = sc.newAPIHadoopRDD(hadoopConf,
                inputFormatClass,
                keyClass,
                NullWritable.class);

However, now it is complaining that inputFormatClass may not have been initialized. I think I'm missing something...

Variables in Java are either null , or an instance. Your variable inputFormatClass is neither null nor an instance, so you can't do anything to it until you initialize it. That's what it's complaining about.

As for passing the class in, you can do:

Class<AvroKeyInputFormat> clazz = AvroKeyInputFormat.class

Generic types are not stored at runtime - they are only used for verification. That's why you can't have a class of AvroKeyInputFormat<AvroFlumeEvent>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM