guy mograbi guy mograbi - 4 months ago 33
Java Question

CGLib - control instance creation

I am using CGLib to enhance class A.

public class A {
public void printName(){

I have class B which extends class A.

public class B extends A{
public void printName(){
System.out.println("someone else!");

How can I tell CGLib to instantiate B instead of A when I enhance it?

public A getEnhancedClass( boolean trueIfIWantBInsteadOfA ){
e.setSuperclass( A.class ); // cannot change this
e.setCallback( createDummyInterceptor() );// an interceptor that just invokesSuper
/// ... missing code here
return (A) e.create()

the following code should print "someone else!"

getEnhancedClass( true ).printName();


Cglib creates a subclass of the arument given in Enhancer#setSuperclass. If you subclass A, the proxy will not even know about the existance of B. Maybe you want to create a lazy proxy? Then you might want to look at the LazyLoader or Dispatcher callback.