AspectJ - Static inter-type declaration on classes implementing a given interface

醉酒当歌 提交于 2020-01-15 11:55:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!