Frage

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?

War es hilfreich?

Lösung

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

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top