0

I am using CGLib to enhance class A.

public class A { 
   public void printName(){
       System.out.println("guy");
   }
}

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();
Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192
guy mograbi
  • 27,391
  • 16
  • 83
  • 122

2 Answers2

1

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.

Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192
0

Maybe you need to intercept the constructor and return an instance of B and not invoke the A constructor.

Raindog
  • 1,468
  • 3
  • 14
  • 28