Java reflection: How do I override or generate methods at runtime?

ivan_ivanovich_ivanoff picture ivan_ivanovich_ivanoff · Jun 28, 2009 · Viewed 31.9k times · Source

It is possible in plain Java to override a method of a class programmatically at runtime (or even create a new method)?

I want to be able to do this even if I don't know the classes at compile time.

What I mean exactly by overriding at runtime:

abstract class MyClass{
  public void myMethod();
}

class Overrider extends MyClass{
  @Override
  public void myMethod(){}
}

class Injector{
  public static void myMethod(){ // STATIC !!!
    // do actual stuff
  }
}

// some magic code goes here
Overrider altered = doMagic(
    MyClass.class, Overrider.class, Injector.class);

Now, this invocation...

altered.myMethod();

...would call Injector.myMethod() instead of Overrider.myMethod().

Injector.myMethod() is static, because, after doing "magic" it is invoked from different class instance (it's the Overrider), (so we prevent it from accessing local fields).

Answer

oxbow_lakes picture oxbow_lakes · Jun 28, 2009

You can use something like cglib for generating code on-the-fly