Search code examples
javaaspectjaopaspects

Aspectj. Creating innter type methods in multiple classes


If I put:

public CountryState CountryState.find(long id) {
        return (CountryState) findById(CountryState.class, id);
}

I'm creating a method find in the class CountryState.

Is there a way to create a method in several classes? Do I need to repeat the code for each class I want to create?

I know that with aspect I can make a class inherit from another, but, doing this, I can create one superclass because java doesn't accept multiple inheritance.


Solution

  • This 'pattern' is how you do it in AspectJ.

    Declare an interface:

    interface Holder {}
    

    Make your intertype declarations on the interface:

    public int Holder.getMeAnInt() {
      return 42;
    }
    

    When you make a declaration like that on an interface you are providing a 'default implementation'. So the interface will now define getMeAnInt() and any implementations of Holder that do not implement getMeAnInt() will get the default implementation.

    The final piece of the puzzle is then to use declare parents to specify which group of types implement your interface:

    declare parents: @Anno * implements Holder;
    

    So now, any type annotated with @Anno will implement Holder and have the getMeAnInt() method.