ByteBuddy not retaining method annotation that was dynamically added via javassist

时间:2019-04-17 02:04:28

标签: byte-buddy

When using bytebuddy, the transformed class does not contain the method annotation: @ProtectionContext that was present on the method before (though added dynamically via javassist).

Note: this issue does not happen when the annotation is hardcoded in the class. It only happens when the annotations are added dynamically

As you can see, the annotations are detected properly in the matcher, so it means that byte buddy received the class with the method annotations.

But after calling unloaded.load(...), the method annotations are no where to be found.

I 've tried everything, but it's not working

                        ElementMatcher<MethodDescription> matcher = new 
                        ElementMatcher<MethodDescription>() {

                        @Override
                        public boolean matches(MethodDescription target) {

                            if (target.isAbstract()) {
                                return false;
                            }

                            for (AnnotationDescription a : target.getDeclaredAnnotations()) {
                                if (a.getAnnotationType().getTypeName().equals(ProtectionContext.class.getName())) {
                                    // System.out.println(target);
                                    return true;
                                }
                            }
                            return false;
                        }
                    };

                   Unloaded<?> unloaded = new ByteBuddy()
                            .with(AnnotationRetention.ENABLED)
                            .rebase(c)
                            .method(matcher)

                      .intercept(MethodDelegation.to(Interceptor.class)
                                 .andThen(SuperMethodCall.INSTANCE)
                       )
                            .make();


                Class<?> c = unloaded.load(...).getLoaded();

               // Annotation not found on c

Adding @Inherited to the @interface ProtectionContext is also not working

1 个答案:

答案 0 :(得分:1)

自己解决这个问题。

重载rebase方法以接受ClassFileLocator,应将其指定为从Javassist请求修改后的字节码