Guice,无法绑定ClassTag[T](要知道T的名字class)
Guice, unable to bind ClassTag[T] (to know the name of T class)
我想知道通用名称 class。
我现在使用的解决方案是下面这个。我定义了 class class A[T: ClassTag] {...}
能够做到 classTag[T].toString
.
这可以编译,但是 Guice 有问题。我收到错误 No implementation for scala.reflect.ClassTag<com.test.Person> was bound
.
有没有:
- 了解可以与 Guice 一起使用的通用 class 名称的另一种解决方案?或
- 一种将
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]) {
}
感谢@tavian-barnes 的帮助,我找到了解决这个问题的方法。
解决方案是向 A
添加一个隐式值 TypeLiteral[T]
。然后,您只需调用 typeLiteral.getType.getTypeName
即可获取 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`
}
我想知道通用名称 class。
我现在使用的解决方案是下面这个。我定义了 class class A[T: ClassTag] {...}
能够做到 classTag[T].toString
.
这可以编译,但是 Guice 有问题。我收到错误 No implementation for scala.reflect.ClassTag<com.test.Person> was bound
.
有没有:
- 了解可以与 Guice 一起使用的通用 class 名称的另一种解决方案?或
- 一种将
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]) {
}
感谢@tavian-barnes 的帮助,我找到了解决这个问题的方法。
解决方案是向 A
添加一个隐式值 TypeLiteral[T]
。然后,您只需调用 typeLiteral.getType.getTypeName
即可获取 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`
}