scala - 在 Scala 中使用反射访问外部类

标签 scala

在Scala中,是否可以使用反射来访问内部类的外部类?例如:

class A { 
   val inner = new { 
      println(getClass.getConstructors.toList)  
      println(getClass.getDeclaredFields.toList)
   }
}

scala> val a = new A
List(public $line11.$read$$iw$$iw$A$$anon$1($line11.$read$$iw$$iw$A))
List()
a: A = A@45f76fc7

我认为 Scala 编译器在某处保存了对外部类的引用,但您可以在这里看到构造函数中打印的字段列表是空的。此外,构造函数似乎引用了外部类实例(但很难确定——我不确定这里到底发生了什么)。我还注意到在某些情况下有一个 $outer这似乎是我需要的领域,但它并不总是在那里,我不明白这一点。

为什么???!!! 我有一个内部类,我需要创建一个使用反射的新实例。新实例是从现有实例复制的,并且需要具有相同的外部引用。

最佳答案

我认为你不能可靠地获得父级,除非你在内部类的构造函数之外使用父级。鉴于:

class X  {
    val str = "xxyy"
    val self = this

    val inner = new {
        override def toString():String = {
            "inner " + self.toString
        }

    }

    override def toString():String = {
        "ima x" + this.str
    }

}

如果你做 javap 你会得到一个私有(private)字段 $outer

但给出:
class X  {
    val str = "xxyy"
    val self = this

    val inner = new {
        println(self)

    }

    override def toString():String = {
        "ima x" + this.str
    }

}

javap 不指示 $outer 字段。

关于scala - 在 Scala 中使用反射访问外部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7325200/

相关文章:

class - 如何实现案例类的实例共享

scalac 在 ScalaTest 测试中发现错误的 forAll 方法

Scala 隐式特化

scala - 如何编写绑定(bind)集合类型和元素类型的通用 Scala 增强方法?

java - 在 Intellij 中导入 Scala 库时出现问题

scala - 如何在 Scala 复制中导入游戏

regex - 在 Scala 中的给定索引之后查找字符串中的正则表达式匹配

r - Spark ML 管道 Logistic 回归产生的预测比 R GLM 差得多

java - 如何使用具有链接本地 ipv6 地址的 Java 或 Scala http 客户端?

scala - 如何通过名称作为ActorRef获得Akka Actor ?