Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a public accessor from an inherited protected Java field

How can I make the following work:

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
}

Note that edits is a protected field in CompoundEdit (a super class of UndoManager). I would like to have a public accessor with the same name that reads that field. How would I do that?

<console>:8: error: super may be not be used on variable edits
         def edits: java.util.Vector[javax.swing.undo.UndoableEdit] = super.edits
                                                                            ^
like image 378
0__ Avatar asked Jan 19 '26 09:01

0__


1 Answers

Well, there's always 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]]
}

You can also disambiguate the two calls by nesting, though this is ugly:

class PreFoo extends javax.swing.undo.UndoManager {
  protected def editz = edits
}
class RealFoo extends PreFoo {
  def edits() = editz
}

You do need the (), though--without it conflicts with the field itself (and you can't override a val with a def).

like image 166
Rex Kerr Avatar answered Jan 21 '26 23:01

Rex Kerr