Access outer anonymous class from inner anonymous class

前端 未结 4 1539
孤城傲影
孤城傲影 2021-02-12 23:25

I\'m just curious. Is there a way to access parent in anonymous class that is inside another anonymous class?

I make this example create a JTable subclass

4条回答
  •  遥遥无期
    2021-02-12 23:49

    In your context, 'super', of course, refers to the Runnable base, not the JTable base. As you know, using 'super' in an inner class refers to the superclass of that inner class, not the superclass of its enclosing class (it does not matter if it's anonymous or not). Since you want to call a method of the JTable base, you must use 'super' in the context of one of the JTable subclass methods.

    You could create a new method in your JTable subclass, e.g. jTableBaseChangeSelection(), that calls the JTable's changeSelection() that you are intending to call. Then you call that from the Runnable subclass:

    public static void main(String args []){
    
        JTable table = new JTable(){
    
            // calls JTable's changeSelection, for use by the Runnable inner
            // class below, which needs access to the base JTable method.
            private void jTableBaseChangeSelection (int row, int column, boolean toggle, boolean extend) {
                super.changeSelection(row, column, toggle, extend);
            }
    
            @Override
            public void changeSelection(
                final int row, final int column,
                final boolean toggle, final boolean extend) {
    
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        // call JTable base changeSelection, since we don't have access
                        // to the JTable base class at this point.
                        jTableBaseChangeSelection(row, column, toggle, extend); 
                        //more code here
                    }
                });
            }
        };
    
    }//end main
    

    Please note, this answer is attempting to retain your original design of an anonymous enclosing class. There are certainly reasons for doing that (and yes, quickly putting together some code is a valid reason in some cases). Having a few isolated situations where this happens -- no harm done; however, you may still wish to rethink your design if you find yourself getting into situations like this often.

提交回复
热议问题