簡體   English   中英

使用字節伙伴從自定義批注中檢索參數

[英]Retrieving parameters from custom annotations using byte-buddy

我需要從自定義批注中檢索參數,並將其傳遞給攔截器。 例如,

@MyAnnotation(id="Some", enumpar=SomeEnum.SOMECONSTANT)
public String sayHello() {
}

我想在以下攔截器中使用值id和enumpar

@RuntimeType
public Object intercept(@SuperCall Callable<?> zuper) throws Exception {
    // interception stuff
    return zuper.call();
}

那么如何擴展基類以包括注釋參數呢? 我現在有以下內容

Class<?> enhancedClass = new ByteBuddy()
        .with(new NamingStrategy.SuffixingRandom("Proxy"))
        .subclass(clazz)
        .method(isAnnotatedWith(MyAnnotation.class))
        .intercept(MethodDelegation.to(new ListenerMetricsInterceptor()))
        .make()
        .load(Thread.currentThread().getContextClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
        .getLoaded();

完全有可能:

@RuntimeType
public Object intercept(@SuperCall Callable<?> zuper,
                        @Origin Method method) throws Exception {
  MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
  // interception stuff
  return zuper.call();
}

默認情況下,方法實例被緩存,因此性能開銷最小。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM