Вопрос

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();
Это было полезно?

Решение

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.

Другие советы

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top