问题
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
^
回答1:
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).
回答2:
You can't change the visibility of an inherited field, this is not allowed.
In some case you could 'simulate' such behavior by using composition, but you won't be able to implement the CompoundEdit class obviously.
Not sure about 'editToBeUndone' as this method doesn't exist in the class: http://docs.oracle.com/javase/6/docs/api/javax/swing/undo/CompoundEdit.html
来源:https://stackoverflow.com/questions/15591901/making-a-public-accessor-from-an-inherited-protected-java-field