从继承的受保护Java字段创建公共访问器 [英] Making a public accessor from an inherited protected Java field
本文介绍了从继承的受保护Java字段创建公共访问器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何进行以下工作:
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
}
注意编辑
是 CompoundEdit
中的受保护字段(超级 UndoManager
)。我想要一个具有相同名称的公共访问器来读取该字段。我该怎么做?
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
^
推荐答案
好吧,总会有反思。
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
}
你确实需要()
- 没有它与字段本身(并且您不能使用 def
覆盖 val
)。
You do need the ()
, though--without it conflicts with the field itself (and you can't override a val
with a def
).
这篇关于从继承的受保护Java字段创建公共访问器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文