简体   繁体   中英

Java Anonymous Inner Class Calling Static Method

I have the following code in an eclipse application:

import org.eclipse.swt.widgets.Listener;
public class X {
  public void test() {
     Listener eclipseListener = new Listener() {
        public void handleEvent(Event evt) {
            System.err.println("starting");
            Y.externalMethod();
            System.err.println("finished");
        }
    }
}

public class Y {
    public static void externalMethod() {
        System.err.println("in class Y");
    }
}

When I run method test in class X, I get the following output:

starting

I don't understand why externalMethod didn't run in class Y and why control didn't return to class X (it never prints 'finished' or 'in class Y').

Any ideas about why externalMethod doesn't run? Are anonymous inner classes not permitted to call static methods outside their class? If so, why does this code compile?

Instead of

    public void handleEvent(Event evt) {
        System.err.println("starting");
        Y.externalMethod();
        System.err.println("finished");
    }

you might have better luck with:

    public void handleEvent(Event evt) {
        System.err.println("starting handleEvent");
        try {
            Y.externalMethod();
        } finally {
            System.err.println("finished handleEvent");
        }
    }

That is,

  1. Put the method exit trace in finally
  2. Add method names to trace lines

The method handleEvent() is not invoked here. What you did is defining anonymous class and create an instance from it on the fly.

You need to register this listener ( eclipseListener ) to some event handler which will invoke the method handleEvent() when an event fires.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM