mercredi 29 avril 2015

Method interceptor for a final quantified method

I'm trying some method interceptor which can intercept a method in a class. I tried using cglib, bytebuddy. I cannot use normal Java proxy class, since it is a class. Is there any way to intercept my final method. Here is, what I've tried so for.

//My Target class,

public class Hello {
    public final  String sayHello(){
    //return lower case hello
    return "hello";
    }
}

//Main Application

public class InterApp {
    public static void main(String[] d) throws Exception {
        new InterApp().loadclassDD();
    }

    public void loadclassDD() throws Exception {
       //Byte-buddy
        Hello helloObject1 = new ByteBuddy()
                .subclass(Hello.class)
                .method(named("sayHello"))
                .intercept(MethodDelegation.to(LoggerInterceptor.class))
                .make()
                .load(getClass().getClassLoader(),
                        ClassLoadingStrategy.Default.WRAPPER).getLoaded()
                .newInstance();
        System.out.println(helloObject1.sayHello());
       //CGLIB
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(Hello.class);
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object arg0, Method arg1, Object[] arg2,
                    MethodProxy arg3) throws Throwable {
                System.out.println("method name " + arg1.getName());
                return arg3.invokeSuper(arg0, arg2).toString().toUpperCase();
            }
        });
        Hello proxy = (Hello) enhancer.create();
        System.out.println(proxy.sayHello());
    }
}

//LoggerInterceptor - Byte-buddy implementation

public class LoggerInterceptor {
public static String log(@SuperCall Callable<String> zuper)throws Exception {
    System.out.println("Method intercepted");
    return zuper.call().toUpperCase();
}
}

If I remove the final quantifier from the method both are working(Providing upper case HELLO as output). What is reason for this.? Is there any way to achieve this? Correct me, if my understanding is wrong.





Aucun commentaire:

Enregistrer un commentaire