title: How can I modify a java.lang class on the fly?
body: <p>I'm looking for a way to add fields to an Thread on the fly by rewriting the byte code and reloading the class, not sure if it is at all possible. Any pointers welcome. I found some info on modifying and loading a class, and I know JRebel can seamlessly hot swap your code but not sure if the same approach/tools apply here.</p>
  
  <p>The motivation here is exploring a theoretically better alternative to thread local objects. Should the method work I should be able to replace thread local with an annotation and the result should outperform current JDK implementation.</p>
  
  <p>PS: Please save me the "root of all evil speech"</p>
  
  <p>Clarifying use case:</p>
  
  <p>Imagine I have a class with a ThreadLocal:</p>
  
  <pre><code>
  class A {
     ThreadLocal&ltCounter&gt counter;
     ...
     counter.get().inc()
  }
  </code></pre>
  
  <p>I'd like to replace that with an annotation:</p>
  
  <pre><code>
  class A {
     @ThreadLocal
     Counter counter;
     ...
     counter.inc()
  }
  </code></pre>
  
  <p>But instead of the above code getting generated I'd like to mutate Thread such that Thread will now have an Acounter field and the actual code will be:</p>
  
  <pre><code>
  class A {
     // Nothing here, field is now in Thread
     ...
     Thread.currentThread().Acounter.inc()
  }
  </code></pre>