1

I'm trying to replace methods in a class with their counterparts in a subpackage, if they exist. For example, if I have a class "name.package.ClassName" and I want to replace its methods with those in "name.package.subpackage.ClassName".

I'm using Byte Buddy and this technique:

new AgentBuilder.Default()
    .type(ElementMatchers.any())
    .transform(new AgentBuilder.Transformer() {
        @Override
        public Builder<?> transform(Builder<?> builder, TypeDescription typeDescription, ClassLoader classloader, JavaModule javaModule, ProtectionDomain protectionDomain) {
            String className = typeDescription.getSimpleName();
            String packageName = typeDescription.getPackage().getName();
            String subPackageName = packageName + ".subpackage";
            try {
                System.err.println("Sub class FOUND for " + className + " in package: " +subPackageName);
                Class<?> subClass = Class.forName(subPackageName+ "." + className);
                return builder
                    .method(ElementMatchers.named("methodName_isWorking")) 
                    .intercept(MethodDelegation.to(subClass));                                    
            } catch (ClassNotFoundException e) {
                System.err.println("Sub class not found for " + className);
            }
        }
    }).installOn(instrumentation);;

The problem is that if I use the method name directly, the replacement works correctly. But I need something dynamic that does it for all methods in the subpackage.

I've tried creating both classes with all methods, but if I use .method(ElementMatchers.any()) it doesn't work.

Can anyone help me with this? Thanks!

I've tried using annotations with ElementMatchers.isAnnotatedWith(AnnotationClass.class), but if I have two methods with the same annotation and different value() (for example @AnnotationClass("hello") and @AnnotationClass("bye"), it doesn't work. If only one method is annotated, it works.

I've also tried using the specific method name and it works, but I need something dynamic that does it for all methods in the subpackage.

I've tried using .method(ElementMatchers.any()) to see if it works for all methods, but it never replaces anything, even if there's only one method or multiple methods.

1
  • Have you tired what you are suggesting, but with an AgentBuilder.Listener? It seems to me that some of your attempts yield an error. Commented Jan 9, 2024 at 20:43

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.