Guice, не в состоянии связать ClassTag[T] (узнать имя класса T)

Я хотел бы знать название универсального класса.

Решение, которое я использую сейчас, следующее. Я определил класс class A[T: ClassTag] {...} быть в состоянии сделать classTag[T].toString,

Это компилируется, но есть проблема с Guice. Я получаю ошибку No implementation for scala.reflect.ClassTag<com.test.Person> was bound,

Есть:

  • Другое решение узнать имя универсального класса, который может работать с Guice? или же
  • Способ связать ClassTag[T] с Guice?

Полный код:

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]) {

}

1 ответ

Решение

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], Тогда вам просто нужно позвонить typeLiteral.getType.getTypeName to get the full name of geneirc class T,

Полный код:

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`

}
Другие вопросы по тегам