title: Java factory pattern - load classes dynamically
body: <p>I have a lot of classes UNO,HAV,MAS,KOS
  I want to create  a factory pattern.</p>
  
  <pre><code> validator.load("UNO").validate();
  </code></pre>
  
  <p>I need dynamically load classes into validator class and return an instance.<br/>
  (dynamically  set name of the class and return an instance)<br/>
  My problem is: how can I return the instance of a class, if I have incompatible types?</p>
  
  <p>I don't know what to write in return type of method.</p>
  
  <p>The main problem in the <strong>Validator CLASS</strong>.</p>
  
  <pre><code>public SegmentAbstract load(String str) {
  </code></pre>
  
  <p>AND</p>
  
  <pre><code>return SegmentAbsClass.forName(identify);
  </code></pre>
  
  <p><strong>Main class</strong></p>
  
  <pre><code>try{
     validator.load("UNO").validate();
  }catch(Exception e){
     System.out.print("No class ");
  }
  </code></pre>
  
  <p><strong>Abstract Class (SegmentAbstract)</strong></p>
  
  <pre><code>public abstract class SegmentAbstract {
  
    public abstract Boolean validate();
  }
  </code></pre>
  
  <p><strong>Class UNO</strong></p>
  
  <pre><code>public class UNA extends SegmentAbstract{
  
    public Boolean validate() {
      System.out.print("UNO!!");
      return true;
    }
  
  }
  </code></pre>
  
  <p><strong>Class Validator</strong></p>
  
  <pre><code>public class Validator {
  
    public SegmentAbstract load(String str) {
      String identify = str.substring(0, 3);
      try {
  
        return SegmentAbsClass.forName(identify);
      }
      catch(Exception e) {
        return this;
      }
  
    }
  }
  </code></pre>