EventBus icon indicating copy to clipboard operation
EventBus copied to clipboard

Can we subscribe an abstract method

Open adhamenaya opened this issue 9 years ago • 3 comments

Can we put the annotation @Subscribe to an abstract method in the parent class only and don't put it to the implementation methods in the child classes?

For example:

abstract class Parent {  
        @Subscribe 
        public abstract void sayHi(EventMessage em); 
}
class ChildA{
        public void sayHi(EventMessage em){
                 System.out.println("Hi I am ChildA");
       }
}

Will the EventBus class the function and print the message ?

adhamenaya avatar Aug 21 '16 12:08 adhamenaya

As far as I know Java does not support annotation inheritance. So this does not work out of the box.

I suppose you could implement the method in your abstract class and then override it in child classes. If you register EventBus within the parent class, it should call the proper child method.

Like

abstract class Parent {  
        @Subscribe 
        public void sayHi(EventMessage em) {
        }
}
class ChildA{
        @Override
        public void sayHi(EventMessage em){
                 System.out.println("Hi I am ChildA");
       }
}

-ut

greenrobot-team avatar Aug 22 '16 12:08 greenrobot-team

Java does not support annotation inheritance

if you need abstract method your code can like this:

abstract  class Parent{

@Subscribe 
public void onEvent(Event event){
   doEvent(event);
}

protected abstract void doEvent(Event event);
}
class Child{
     @Override
     protected void doEvent(Event event){
   // do something
 }
}

keluokeda avatar Sep 11 '16 15:09 keluokeda

See two workarounds above. Keeping this open for future reference if we ever want to support this. -ut

greenrobot-team avatar Sep 19 '16 08:09 greenrobot-team