0

Let's consider that I have some Class A which has property of class B.

public class ClassA{

private ClassB classB; 

public ClassA(ClassB classB){
 this.classB = classB;
}

 //some methods ommitted.
}

No I have CGLIB proxy:

public class CGLibProxy  implements MethodInterceptor{

    @Override
    public Object intercept(Object object, Method method, Object[] args,
            MethodProxy methodProxy) throws Throwable {

    if (method.getName().startsWith("print")){
        System.out.println("We will not run any method started with print"); 
        return null;
    }
        else
        return methodProxy.invokeSuper(object, args);
    }
}

Now, When I use CGLib for ClassA , proxy creates ClassA instance.

My question is how can I pass classB parameter to this proxy, because as far As I understand CGLib will run empty constructor for ClassA?

danny.lesnik
  • 18,479
  • 29
  • 135
  • 200

1 Answers1

7

I do not see any code examples on how you are wrapping ClassA in with the CGLibProxy class but if you are dealing with cglib directly then you should have a instance of net.sf.cglib.proxy.Enhancer in that case you can supply the constructor args as follows.

import net.sf.cglib.proxy.Enhancer;

public class CGLibProxyMain {

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(ClassA.class);
        enhancer.setCallback(new CGLibProxy());
        ClassA a = (ClassA) enhancer.create(new Class[] {ClassB.class}, new Object[] {new ClassB()});
        System.out.println(a.printB());;
        System.out.println(a.otherMethod());
    }
}
Patrick
  • 651
  • 6
  • 14