title: Java: What is the fastest way to inject fields using reflection?
body: <p>Suppose, I have a lot of classes, which are constructed using Java reflection (for some reason). Now I need to post-inject values to fields, which are 
  annotated with <code>@PostInject</code>.</p>
  
  <pre><code>public class SomeClass {
    @PostInject
    private final String someString = null;
  
    public void someMethod() {
      // here, someString has a value.
    }
  }
  </code></pre>
  
  <p>My question is: <strong>what is a fast way to set a field using reflection?</strong><br>
  Remember, I need to do this very often on a lot of classes, that's
  why performance is relevant.</p>
  
  <p>What I would do by intuition is shown by this pseudo-code:</p>
  
  <ul>
  <li>get all fields of the class<br>
  <code>clazz.getFields();</code></li>
  <li>check, which are annotated with @PostInject<br>
  <code>eachField.getAnnotation(PostInject.class);</code></li>
  <li>make these fields accessible<br>
  <code>eachAnnotatedField.setAccessible(true);</code></li>
  <li>set them to a certain value<br>
  <code>eachAnnotatedField.set(clazz, someValue);</code></li>
  </ul>
  
  <p>I'm afraid that getting all fields is the slowest thing to do.<br>
  Can I someone get a field, when I know it from the beginning?</p>
  
  <p><em>NOTE: I can't just let the classes implement some interface, which would
  allow to set the fields using a method. I need <strike>POJOs.</strike></em></p>
  
  <p><em>NOTE2: Why I want post-field injection: From the point of view of an API user, it must be possible to use final fields. Furthermore, when the types and number of fields are not known by the API a priori, it is impossible to achieve field initialization using an interface.</em></p>
  
  <p><em>NOTE2b: From the point of view of the user, the final contract is <strong>not</strong> broken. It stays final. First, a field gets initialized, then it can't be changed. By the way: there are a lot of APIs which use this concept, one of them is JAXB (part of the JDK).</em></p>