Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving parameters from custom annotations using byte-buddy

I need to retrieve parameters from a custom annotation and pass them in an interceptor. For example,

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

I'd like to use the values id and enumpar in the following interceptor

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

So how can I extend the base class to include the annotation parameters? I have the following right now

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();
like image 350
devin Avatar asked Sep 23 '26 13:09

devin


1 Answers

It is perfectly possible:

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

By default, the method instance is cached so the performance overhead is minimal.

like image 83
Rafael Winterhalter Avatar answered Sep 26 '26 02:09

Rafael Winterhalter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!