Eventbus: Can we subscribe an abstract method

Created on 21 Aug 2016  路  3Comments  路  Source: greenrobot/EventBus

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 ?

Most helpful comment

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
 }
}

All 3 comments

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

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
 }
}

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

oky2abbas picture oky2abbas  路  6Comments

cckroets picture cckroets  路  16Comments

veeti picture veeti  路  3Comments

lordcodes picture lordcodes  路  3Comments

DavidEdwards picture DavidEdwards  路  11Comments