如何在运行时加载Scala类,并尝试获取ClassTag并使用此类型信息创建泛型类

时间:2016-10-08 00:57:50

标签: scala generics

有一个通用的方法如下:

def saveAvro[T](inputPath: String, outputPath: String, context: SQLContext, rowTag: String)(implicit et: ClassTag[T]) {
    ...
    Option(jaxbUnmarshaller.unmarshal(new StringReader(xml._1.toString())).asInstanceOf[T] )
    ...
    nrdd.saveAsNewAPIHadoopFile(outputPath, className,
    classOf[org.apache.hadoop.io.NullWritable],
    classOf[AvroKeyOutputFormat[T]],
    job.getConfiguration)
     ...
   }

如果工作正常,但是当我们需要另一个级别泛型和动态加载类时,通过给出类完整包路径,如com.xxx.xxx.classname,我们尝试更改为类似下面的内容,而不是给出ClassTag[T]

def saveAvro(fullclasspath: String, inputPath: String, outputPath: String, context: SQLContext, rowTag: String){

    val klazz = Class.forName(fullclasspath)
    //how to do asInstance[T] ???
    //How to get classOf[AvroKeyOutputFormat[T]] ???
 }

0 个答案:

没有答案