title: Dynamically loading classes which adhere to an interface
body: <p>I have several classes which implement two interfaces. All of them implement the <em>BaseInterface</em> and some other interface which is specific to them.</p>
  
  <p>I want to be able to use the <em>loadClass</em> method below to instantiate classes which are referred to in a <em>.properties</em> file and call the common method they all contain (because they implement <em>BaseInterface</em>).</p>
  
  <pre><code>public interface BaseInterface {
      public void doBase();
  }
  
  public interface SpecificInterface extends BaseInterface {
      public void doSpecific();
  }
  
  public class SpecificClass implements SpecificInterface {
      public void doBase() { ... }
  
      public void doSpecific() { ... }
  }
  
  public class LoadClass() {
      private PropertiesLoader propertiesLoader = new PropertiesLoader();
  
      public &lt;C extends BaseInterface&gt; C loadClass(String propertyName) {
          Class&lt;C&gt; theClass;
  
          // Load the class.
          theClass = propertiesLoader.getPropertyAsClass(propertyName);
  
          // Create an instance of the class.
          C theInstance = theClass.newInstance();
  
          // Call the common method.
          theInstance.doBase();
  
          return theInstance;
      }
  }
  </code></pre>
  
  <p>Unfortunately, when I run the code:</p>
  
  <pre><code>loadClassInstance.loadClass("SpecificClass");
  </code></pre>
  
  <p>I get the following exception:</p>
  
  <pre><code>Exception in thread "main" java.lang.ClassCastException:
  SpecificClass cannot be cast to BaseInterface
  at LoadClass.loadClass
  </code></pre>
  
  <p>Any ideas how I would solve this issue?</p>
  
  <p>Many Thanks, Danny</p>