我正在引导自己进入Scala,并且正在努力解决为什么编译器在以下来源中禁止classOf[Hello]
。
package example
import org.slf4j.LoggerFactory
object Hello extends Greeting with App {
val logger = LoggerFactory.getLogger(classOf[Hello])
logger.info(s"greeting is $greeting")
println(greeting)
}
trait Greeting {
lazy val greeting: String = "hello"
}
编译器抱怨
[info] Compiling 2 Scala sources to /Users/robert.kuhar/dev/hellosbt/target/scala-2.12/classes ...
[error] /Users/robert.kuhar/dev/hellosbt/src/main/scala/example/Hello.scala:6:48: not found: type Hello
[error] val logger = LoggerFactory.getLogger(classOf[Hello])
[error] ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 1 s, completed Dec 17, 2017 1:20:28 PM
Hello是类Hello的单例,不是吗?在我的应用程序中利用常见的“Logger Name is Class Name”来实例化记录器需要什么?
答案 0 :(得分:1)
因为您无法获得object
的类型。
scala> object MySingleton
defined object MySingleton
scala> classOf[MySingleton]
<console>:12: error: not found: type MySingleton
classOf[MySingleton]
^
另外,请注意当您将单例分配给变量时,键入的内容为MySingleton.type
scala> object MySingleton { def foo = "bar" }
defined object MySingleton
scala> val x = MySingleton
x: MySingleton.type = MySingleton$@4ffe3d42
scala> x.foo
res3: String = bar
通常情况下,我在单个对象中创建记录器,但是参考该类。
import org.slf4j.LoggerFactory
class Hello
object Hello extends Greeting with App {
val logger = LoggerFactory.getLogger(classOf[Hello])
logger.info(s"greeting is $greeting")
println(greeting)
}
trait Greeting {
lazy val greeting: String = "hello"
}
另一种方法是使用方法.getClass
scala> object MySingleton
defined object MySingleton
scala> MySingleton.getClass
res1: Class[_ <: MySingleton.type] = class MySingleton$