Create an open accessor from a legacy Java protected field

How can I do 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 (superclass of UndoManager ). I would like to have an open accessory with the same name that reads this field. How can I do it?

 <console>:8: error: super may be not be used on variable edits def edits: java.util.Vector[javax.swing.undo.UndoableEdit] = super.edits ^ 
+3
source share
2 answers

Well, there is always a 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 eliminate two calls by nesting, although this is ugly:

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

You need () , although this does not contradict the field itself (and you cannot override val with def ).

+2
source

You cannot change the visibility of an inherited field; this is not allowed.

In some cases, you can "simulate" this behavior using composition, but you cannot implement the CompoundEdit class, obviously.

Not sure about 'editToBeUndone' since this method does not exist in the class: http://docs.oracle.com/javase/6/docs/api/javax/swing/undo/CompoundEdit.html

+1
source

Source: https://habr.com/ru/post/1481369/


All Articles