问题
I would like to know if it is possible (and how if it is...) to make a static inter-type declaration that works on all classes that implements a given interface.
In my use case, I have an empty interface:
public interface Delegate {}
and two classes implementing it:
public class DelegateA implements Delegate {...}
public class DelegateB implements Delegate {...}
And I want an aspect to declare a static member on DelegateA and DelegateB... and all the future classes that will implements my interface !
How should I do it ? If it's only possible...
回答1:
Are you sure that you want to do that? In any case, here is my best solution for your problem:
public aspect MyAspect pertypewithin(Delegate+){
public int oneFieldPerClass;
}
This will instantiate an aspect for each subtype of Delegate. You can access the field in the following ways:
MyAspect.aspectOf(DelegateA.class).oneFieldPerClass = 1;
MyAspect.aspectOf(DelegateB.class).oneFieldPerClass = 2;
Delegate d = new DelegateA();
MyAspect.aspectOf(d.getClass()).onFieldPerClass = 3;
The following thread might be helpful as well:
AspectJ - Creating a global Logger field using an Inter-Type Declaration
HTH, dsp
来源:https://stackoverflow.com/questions/20363873/aspectj-static-inter-type-declaration-on-classes-implementing-a-given-interfac