Access anonymous or local inner class in anonymous or local inner class

Ok, so I know how to access an outer class that includes an inner class, whether anonymous or inner.

But my question is: how to access the outer class if it is itself an inner class? Some code to help:

public final class LocationPage extends BasePage { private static final String CRITERIA_FORM_ID = "CriteriaForm"; protected Panel onCreateBodyPanel() { return new ViewBodyPanel(BasePage.BODY_PANEL_ID) { public void invokeMe() { // How do I Invoke This Method? } private Form<CriteriaBean> helpCreateCriteriaForm() { return new Form<CriteriaBean>(LocationPage.CRITERIA_FORM_ID) { @Override protected void onSubmit() { LocationPage.this.ViewBodyPanel.invokeMe(); // Compile Error. } }; } }; } } 

UPDATE: For those who want to see what I'm trying to do here, here is a complete code example. This is actually an Apache Wicket, but I think you can get this idea. Take a look at the method called onSubmit . I added a code comment to help define it.

UPDATE TWO: Made a code sample to the point. Sorry for that!

+4
source share
2 answers

You only need to specify ParentClass.this.something to fix the error. If your form does not have an invokeMe method, you can simply use the name without qualification, and the compiler should find it:

  private Form<CriteriaBean> helpCreateCriteriaForm() { return new Form<CriteriaBean>(LocationPage.CRITERIA_FORM_ID) { @Override protected void onSubmit() { invokeMe(); } }; } 

If a function exists in an inner inner class, there is no trick in Java to do this. Rather, rename or wrap your ViewBodyPanel.invokeMe method into something that is explicit.

  public void vbpInvokeMe(){ invokeMe(); } private Form<CriteriaBean> helpCreateCriteriaForm() { return new Form<CriteriaBean>(LocationPage.CRITERIA_FORM_ID) { @Override protected void onSubmit() { vbpInvokeMe(); } }; } 
+1
source

Ok, so I know how to access the outer class that surrounds the inner class, regardless of whether it is anonymous or inner.

If you use inner classes , you can do the following

 public class A{ public void printHello(){ System.out.println("Hello!"); } class B{ public void accessA(){ A.this.printHello(); } } } 
0
source

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


All Articles