Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending class at runtime

So for this project I am trying to extend a class at runtime. What I would like to know, is this even possible? If so, how would I do it? Are there libraries out there for these things?

like image 534
PaulBGD Avatar asked Oct 07 '13 20:10

PaulBGD


1 Answers

CGLib is a library you're looking for. It's quite powerfull in extending classes or implementing interfaces in runtime, so many popular frameworks, like Spring or Hibernate use it.

You can create class extension with code like

 public Object createProxy(Class targetClass) {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(targetClass);
    enhancer.setCallback(NoOp.INSTANCE);
    return enhancer.create();
   }

although you would probably replace NoOp callback with a useful method interceptor with desired logic.

like image 152
Jk1 Avatar answered Oct 05 '22 23:10

Jk1