![](/img/trans.png)
[英]@AspectJ pointcut for methods that override an interface method with an annotation
[英]Aspectj pointcut method with annotation in subclass
我有2節課
class Fragment1{
createView(SomeObject p1, AnoterObject p2)
}
@AutoLayout(String annotationParam)
class Fragment2 extends Fragment1{
}
我如何在Fragment2.createView調用上執行@Around createView並獲取AnnotationParam? 謝謝
添加:如果我將方法存根添加到Fragment2中,則可以開始使用下一個注釋@Around("createMethod(inflater, group, savedState) && @within(autoInflate)")
,但這是一個非常丑陋的解決方案
解決方案:感謝@kriegaex,我找到了解決方案:
@Around("execution(* com.github.a_kokulyuk.kotakt.ui.BaseFragment+.*(*, *, *)) && args(inflater, parent, savedState) && @this(an)")
public Object doLayout(ProceedingJoinPoint jo, LayoutInflater inflater, ViewGroup parent, Bundle savedState, AutoLayout an) throws Throwable {
return inflater.inflate(an.value(), parent, false);
}
給定此注釋:
package de.scrum_master.app;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {}
讓我們假設我們有三個類:
package de.scrum_master.app;
public class Parent {
public void doSomething() {}
}
package de.scrum_master.app;
public class PlainChild extends Parent {
int doSomethingElse() { return 11; }
}
package de.scrum_master.app;
@MyAnnotation
public class AnnotatedChild extends Parent {
String doSomethingSpecial(int number) { return ""; }
}
這是一個小小的驅動程序應用程序,實例化所有三個類,並使用不同的簽名和返回類型調用它們上的所有可用方法(是否繼承):
package de.scrum_master.app;
public class Application {
public static void main(String[] args) {
new Parent().doSomething();
new PlainChild().doSomething();
new PlainChild().doSomethingElse();
new AnnotatedChild().doSomething();
new AnnotatedChild().doSomethingSpecial(123);
}
}
最后,這里是做什么用問問題的方面:它截取所有方法執行Parent
或任何其子類(因而+
),但前提是類當前實例的this
熊@MyAnnotation
:
package de.scrum_master.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
@Aspect
public class MyAspect {
@Around(
"execution(* de.scrum_master.app.Parent+.*(..)) && " +
"@this(de.scrum_master.app.MyAnnotation)"
)
public Object myAdvice(ProceedingJoinPoint thisJoinPoint) {
System.out.println(thisJoinPoint);
System.out.println(" " + thisJoinPoint.getThis());
return thisJoinPoint.proceed();
}
}
控制台日志:
execution(void de.scrum_master.app.Parent.doSomething())
de.scrum_master.app.AnnotatedChild@681a9515
execution(String de.scrum_master.app.AnnotatedChild.doSomethingSpecial(int))
de.scrum_master.app.AnnotatedChild@13221655
如您所見, doSomething()
被調用了三次,但僅被攔截了一次。 您還可以從打印的getThis()
對象中看到,確實正確的執行被攔截了。
這是例子
public @interface customAnnotation {
String value() default "someValue";
}
@Aspect
public class customAspect {
@Around(value="@annotation(customAnnotation)")
public Object customAdvice(ProceedingJoinPoint joinPoint, CustomAnnotation customAnnotation ) throws Throwable {
// ...
}
}
如下所示,摘錄摘錄受這些資源的啟發
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.