【问题标题】:Grabbing a simple class name for a class defined in the interpreter为解释器中定义的类获取一个简单的类名
【发布时间】:2014-08-17 16:34:48
【问题描述】:

无论该类是在解释器中还是在 Scala 代码文件中定义的,我都想获得一个简单的类名。您无法从解释器中定义的类中获得简单的名称(请参阅here)。结果,我尝试创建一个只获取完全限定名称的方法,将其拆分为.,然后获取最后一个字符串:

def simpleNameOf(i: AnyRef) = i.getClass.getName.split('.').last

然而,事情变得奇怪了。

scala> def simpleNameOf(i: AnyRef) = i.getClass.getName.split('.').last
simpleNameOf: (i: AnyRef)String

scala> simpleNameOf(new Human)
res25: String = $read$Human

scala> var h = new Human
h: Human = Human@fdad4ab

scala> h.getClass.getName
res27: 字符串 = 人类

scala> h.getClass.getName == "人类"
res28: Boolean = false

scala> h.getClass.getName.length
res29: Int = 44

scala> h.getClass.getName.split('.')
res30: 数组 [字符串] = 数组($line102, $read$Human)

scala> "人类".split('.')
res31: Array[String] = Array(Human)

那么来自getClass.getName 44 个字符的字符串 Human 到底有多长? $line102 和 $read$Human 是从哪里来的?

这是 Scala 2.10.4

【问题讨论】:

    标签: scala


    【解决方案1】:

    这是-Yrepl-class-based 的另一个用例:

    $ scala
    Welcome to Scala version 2.11.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_11).
    Type in expressions to have them evaluated.
    Type :help for more information.
    
    scala> class Foo
    defined class Foo
    
    scala> classOf[Foo].getSimpleName
    java.lang.InternalError: Malformed class name
      at java.lang.Class.getSimpleName(Class.java:1317)
      ... 33 elided
    
    scala> :q
    $ scala -Yrepl-class-based
    Welcome to Scala version 2.11.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_11).
    Type in expressions to have them evaluated.
    Type :help for more information.
    
    scala> class Foo
    defined class Foo
    
    scala> classOf[Foo].getSimpleName
    res0: String = Foo
    

    可以关闭cruft的输出过滤:

    scala> $intp.isettings.unwrapStrings
    res2: Boolean = true
    
    scala> $intp.isettings.unwrapStrings = false
    $intp.isettings.unwrapStrings: Boolean = false
    
    scala> class Bar
    defined class Bar
    
    scala> classOf[Bar].getName
    res3: String = $line12.$read$$iw$$iw$Bar
    

    如果这对你有吸引力。

    最后一个问题:每一行都包含在一个对象(或类)中,该对象(或类)通常嵌套很深,以便于从历史中确定导入的范围。 (如果需要局部块语义,可以使用大括号。)每一行都有一个行包。

    更新:getSimpleName 问题有一张票,这是由于 IIRC 只是由于损坏名称中的双“$$”。嵌套对象会发生这种情况,而不是类(在 Scala 意义上)。

    【讨论】:

    • -Yrepl-class-based的解释:scrapcodes.tumblr.com/post/79260275559/…
    • @IonuțG.Stan 还有其他被交换机解决的行为,与 JIT 相关。
    • 如果能解释一下这个开关是如何解决问题的,那将会很有用。就我个人而言,我不太了解解决方案。
    • 我的理解是,它基本上不会用 REPL 历史/自动完成所需的元信息来装饰类。谢谢 som-snytt
    猜你喜欢
    • 1970-01-01
    • 2012-02-09
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 2023-03-21
    • 2012-07-27
    • 2011-09-29
    • 1970-01-01
    相关资源
    最近更新 更多