title: Java reflection: How do I override or generate methods at runtime?
body: <p>It is possible in plain Java to override a method of a class 
  programmatically at runtime (or even create a new method)?</p>
  
  <p>I want to be able to do this even if I <strong>don't</strong> know the classes at compile time.</p>
  
  <p>What I mean exactly by overriding at runtime:</p>
  
  <pre><code>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);
  </code></pre>
  
  <p>Now, this invocation...</p>
  
  <pre><code>altered.myMethod();
  </code></pre>
  
  <p>...would call <strong>Injector.myMethod()</strong> instead of <strong>Overrider.myMethod()</strong>.</p>
  
  <p>Injector.myMethod() is <strong>static</strong>, because, after doing "magic"
  it is invoked from different class instance (it's the Overrider),
  (so we prevent it from accessing local fields).</p>