title: Is there an alternative to loading a class with Class.forName()?
body: <p>In my library's code, I load class names from an XML file using JAXB, in order to instanciate them later on using <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#forName%28java.lang.String%29" rel="noreferrer"><code>Class.forName()</code></a>. A fictive example to illustrate the case:</p>
  
  <pre><code>public void libraryMethod() throws Exception {
    List&lt;String&gt; classNames = loadClassNamesFromXML();
  
    for (String className : classNames) {
      Class.forName(className).newInstance().doThings();
    }
  }
  </code></pre>
  
  <p>Now, some users use OSGi to configure their applications, and they load my library with a different class loader than the classes they configure using my XML structure. This means that loading may fail, as the class cannot be found.</p>
  
  <p>Is there any more reliable way to load such classes? Or is there any other way to configure these instances? I'm open to suggestions that result in this:</p>
  
  <pre><code>public void libraryMethod() throws Exception {
    // Spring does things like this:
    List&lt;SomeType&gt; instances = loadInstancesFromXML();
  
    for (SomeType instance : instances) {
      instance.doThings();
    }
  }
  </code></pre>
  
  <p>Some constraints:</p>
  
  <ul>
  <li>From a library perspective, the lifecycle of those instances is unimportant. If they have (user) state, my library would not notice.</li>
  <li>I want to keep things simple in this library, so I want to avoid creating external dependencies on configuration frameworks like spring, for instance. So I'm only interested in solutions that can be achieved with standard JDK 6+ distributions.</li>
  <li>I would really like to keep my simple XML configuration file (slight adaptations to the XML structure are OK).</li>
  </ul>