Accessing services inside inner and anonymous classes has been created by Clement Escoffier (Jul 28, 2008).

Content:

Accessing services inside inner and anonymous classes

An inner class is a class defined inside another class. This mechanism is useful in order to avoid creating a bunch of small files. So, it is common when creating threads, Swing listeners ... Generally speaking, inner classes are regular classes treated as separate classes. However this is an oversimplification. Some of the information about an inner class is not in its class file. See section 4.7.5 for further details:
http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html

An inner class can access fields of its outer class. However, when using a field managed by iPOJO, such as a service dependency, the injected object is not accessible. The reason of this behavior is that the inner class accesses the field directly and not with the "injected" getter.

In order to access managed fields, you need to create your own getter method and call it instead of accessing the field directly.

public class AClass {
    private Service m_service; // Injected service

    private void launchAThread() {
      // This is an anonymous class
      Runnable thread = new Runnable() {
        public void run() {
          // ...
          // Access throught a getter method
          getService().doSomething();
          // ...
        };
      thread.start();
    }

    private Service getService() { // Getter method to add
        return m_service;
    }
}
Overview
Getting Started
User Guide
Tools
Developer Guide
Misc & Contact

Reply via email to