0
我正在嘗試在我的團隊的一些代碼中使用AspectJ來添加統計信息追蹤,而不會混淆主要實現,但會遇到一些問題。我想要做的是將特定接口上的方法的所有調用都包圍在我的自定義邏輯中。對於實驗目的,我把一些代碼瓦特/使用泛型:在AspectJ中使用泛型
public interface Dummy {
public void setState(String state);
public String getState();
}
public class DummyImpl implements Dummy {
private String state;
public DummyImpl() { state = "default"; }
public void setState(String state) { this.state = state; }
public String getState() { return state; }
public static void main(String[] args) {
DummyImpl dummy = new DummyImpl();
dummy.setState("One");
dummy.setState("Another");
dummy.setState("OneMore");
System.out.printf("Current state is %s.\n", dummy.getState());
}
}
public aspect BoundDummy {
void around(Dummy d): execution(void Dummy.setState(String)) && target(d) {
String oldState = d.getState();
proceed(d);
System.err.printf("State has changed from \"%s\" to \"%s\".\n", oldState, d.getState());
}
}
這有讓類似的輸出想要的效果: 當前狀態爲OneMore。 狀態已從「默認」更改爲「一個」。 國家已從「一」改爲「另一」。 狀態已從「另一個」更改爲「OneMore」。
現在我嘗試引入泛型,它直接用於接口和實現,但證明對方面更加困難,因爲我不能再使用「目標」並且必須使其變得抽象(如果我不是我得到一個錯誤:「只有抽象方面可以有類型參數」):
public interface Dummy<T> {
public void setState(T state);
public T getState();
}
public class DummyImpl<T> implements Dummy<T> {
private T state;
public DummyImpl(T state) { this.state = state; }
public void setState(T state) { this.state = state; }
public T getState() { return state; }
public static void main(String[] args) {
DummyImpl<String> dummy = new DummyImpl<String>("default");
dummy.setState("One");
dummy.setState("Another");
dummy.setState("OneMore");
System.out.printf("Current state is %s.\n", dummy.getState());
}
}
public abstract aspect BoundDummy<T> {
void around(Dummy<T> d): execution(void Dummy.setState(T)) && target(d) { // <-- doesn't compile due to erasure
T oldState = d.getState();
proceed(d);
System.err.printf("State has changed from \"%s\" to \"%s\".\n", oldState, d.getState());
}
}
在這裏有什麼愚蠢的東西嗎?任何人都可以向我解釋爲了讓代碼在引入泛型之前按照它的方式運行,我必須改變什麼?