开发者

Aspectj. Creating innter type methods in multiple classes

开发者 https://www.devze.com 2023-01-16 10:10 出处:网络
If I put: public CountryState CountryState.find(long id) { return (CountryState) findById(CountryState.class, id);

If I put:

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

I'm c开发者_Python百科reating 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.


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.


You can actually solve it without using AOP. You could just use OOP/OOD. There are two ways (I assume you want to write method once):

  1. Create abstract base class with the method implementation and derive all classes from it. This not the best idea, actually.

  2. Creating helper class that will implement your find() method and share it between classes (either using Dependency Injection, or just by coupling them tightly).

So if I understand it correctly, what you want actually is a generic method that will return instances of the target class:

public <T> find(long id, T targetClassObject) {
  Class<? extends T> class = targetClassObject.getClass();
  // do something i.e. call target method via reflection
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号