我该如何做以下工作:

class Foo extends javax.swing.undo.UndoManager {
  // increase visibility - works for method
  override def editToBeUndone: javax.swing.undo.UndoableEdit = super.editToBeUndone

  // fails for field
  def edits: java.util.Vector[javax.swing.undo.UndoableEdit] = super.edits
}

请注意,editsCompoundEdit(UndoManager的超类)中的一个受保护字段。我想要一个公共访问器,其名称与读取该字段的名称相同。我该怎么做?
<console>:8: error: super may be not be used on variable edits
         def edits: java.util.Vector[javax.swing.undo.UndoableEdit] = super.edits
                                                                            ^

最佳答案

好吧,总有反射Reflection 。

class Foo extends javax.swing.undo.UndoManager {
  def edits(): java.util.Vector[javax.swing.undo.UndoableEdit] =
    classOf[javax.swing.undo.CompoundEdit].
    getDeclaredField("edits").get(this).
    asInstanceOf[java.util.Vector[javax.swing.undo.UndoableEdit]]
}

您也可以通过嵌套消除两个调用的歧义,尽管这很丑陋:
class PreFoo extends javax.swing.undo.UndoManager {
  protected def editz = edits
}
class RealFoo extends PreFoo {
  def edits() = editz
}

不过,您确实需要(),但它不会与字段本身冲突(并且您不能使用val覆盖def)。

09-28 04:27