Question

I have an abstract class that a child class extends. My abstract class has an @Activate method, so does the child class. When OSGi creates my service, it invokes the child class activate method but never the abstract class's activate. Is there any way to force the abstract class's activate to be called by OSGi rather than having the child class manually call the parent activate method?

Here is some code to help elaborate on what I am asking.

@Component(componentAbstract=true, inherit=true)
@Service(value=ISomeInterface)
public abstract class AbstractHello implements ISomeInterface{
    @Activate
    public void activate(){
        System.out.print("Hello ");
    }
}

@Component
@Service(Value=ISomeInterface)
public class World extends AbstractHello{
    @Activate
    public void activate(){
        System.out.println("World!");
    }
}

The result of the code above would be "World!", rather than "Hello World!".

Initially I thought maybe the child activate method name was clobbering the abstract activate method of the same name. The result is the same even if the abstract class's activate method is given a unique name. Is there any way to have OSGi call the abstract class's activate method for me?

Was it helpful?

Solution

The DS annotation processors only look at the concrete class decorated with @Component. Super classes are not examined. Since the annotation processing is done at build time, super types may come from imported packages which are not chosen until runtime.

Also, the annotation processor generates component description XML from the annotations. So there can only be one activate="methodName" attribute in the XML. If you need the superclass' method called, then you need to call it from the subclass' method.

OTHER TIPS

This has nothing to do with Apache Felix and OSGi, this is caused by poor understanding of Class Inheritance and Method Overriding in Java.

Your World class extends AbstractHello class and overrides its activate() method. If you want the AbstractHello.activate() method to be called then you must call it in

// Annotations excluded for readability.
public class World extends AbstractHello {
    public void activate() {
        super.activate();
        System.out.println("World!");
    }
}

OSGi can't help here.

UPDATE

Since the base class is abstract, and you don't have an instance of it, you can't call its method. Neither can OSGi container.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top