Dnomyar Dnomyar - 2 months ago 10
Scala Question

Guice, unable to bind ClassTag[T] (to know the name of T class)

I would like to know the name of a generic class.

The solution I use now is the following one. I defined the class

class A[T: ClassTag] {...}
to be able to do
classTag[T].toString
.

This compiles, but there is a problem with Guice. I get the error
No implementation for scala.reflect.ClassTag<com.test.Person> was bound
.

Is there :


  • Another solution to know the name of a generic class that could work with Guice ? or

  • A way to bind
    ClassTag[T]
    with Guice ?



Full code :

package com.test

case class Person(age: Int)

class A[T: ClassTag] {

// I need to know the (full) name of type T (e.g. com.test.Person)
val tClassName = classTag[T].toString

}

class B @Inject()(a: A[Person]) {

}

Answer

Thanks to @tavian-barnes help, I found the way to solve this problem. The solution is to add to A an implicit value TypeLiteral[T]. Then, you just have to call typeLiteral.getType.getTypeName to get the full name of geneirc class T.

Full code :

package com.test

case class Person(age: Int)

class A[T]()(implicit val typeLiteral: TypeLiteral[T]) {

  val tClassName = typeLiteral.getType.getTypeName

}

class B @Inject()(a: A[Person]) {

    println(a.tClassName) // prints `com.test.Person`

}
Comments