ardalan foroughi pour
ardalan foroughi pour

Reputation: 83

ByteBuddy invoking a method from super class which has been overwritten in child

I am using ByteBuddy to dynamically create a like B in this example:

class A{
    public void greet(String name){
        System.out.println("Hello from class A "+ name + "!");
    }
}

class B extends A{
    public void greet(String name){
        System.out.println("Hola from class B "+ name + "!");
    }

    public void superGreet(String name){
        super.greet(name);
    }
}

And this is my code:

Class<?> dynamicType = new ByteBuddy()
                .subclass(A.class)
                .name("B")
                .defineMethod("superGreet", void.class, Modifier.PUBLIC)
                .withParameters(String.class)
                .intercept(
                        MethodCall.invoke(A.class.getMethod("greet", String.class))
                                .withAllArguments()
                )
                .defineMethod("greet", void.class, Modifier.PUBLIC)
                .withParameters(String.class)
                .intercept(MethodDelegation.to(new MyInterceptor()))
                .make()
                .load(Test.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
                .getLoaded();

        Object obj = dynamicType.newInstance();
        dynamicType.getMethod("superGreet", String.class).invoke(obj, "name");

when I execute this code superGreet invokes method in Class B not Class A. How can I make ByteBuddy invoke the greet method in A ?

Upvotes: 0

Views: 250

Answers (1)

Rafael Winterhalter
Rafael Winterhalter

Reputation: 44007

You have to specify the MethodCall::onSuper invocation target after invoke.

Upvotes: 1

Related Questions