Harel Gliksman
Harel Gliksman

Reputation: 764

How to get scala's TypeTag and ClassTag in java

I am writing Java code in which I need to call a Scala function that is defined like so:

def func[T: TypeTag: ClassTag ](name: String): RDD[T] = ...

In Scala I'd simple call func String The Java code should be something like: func( "a" , arg1 , arg2 ) where arg1 is a TypeTag< T > and arg2 is a ClassTag< T >

I am not sure how to generate arg1 and arg2 in java

Upvotes: 4

Views: 3678

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170919

Do you want to do it for generic T or for specific one? For generic, there is no way to do it, accept ClassTag<T> and TypeTag<T> as arguments instead (just like Scala code actually does). For specific, I'd suggest writing a wrapper in Scala, e.g. def func_String(name: String) = func[String](name) and calling it from Java.

Or more generically, but undesirably complex:

import scala.reflect.ClassTag
import scala.reflect.runtime.universe._

def func1[T](name: String, clazz: Class[T]) = {
  val classTag = ClassTag[T](clazz)

  val m = runtimeMirror(clazz.getClassLoader)
  val tpe = m.classSymbol(clazz).toType
  val typeCreator = new scala.reflect.api.TypeCreator {
    def apply[U <: Universe with Singleton](m1: scala.reflect.api.Mirror[U]): U # Type = 
      if (m1 != m) throw new RuntimeException("wrong mirror") else tpe.asInstanceOf[U#Type]
  }
  val typeTag = TypeTag[T](m, typeCreator)

  func(name)(typeTag, classTag)
}

(you could write the equivalent in Java as well.)

Upvotes: 1

Related Questions