title: Create class instance from class name
body: <p>I have something like this:</p>
  
  
  
  <pre class="lang-java prettyprint-override"><code>@Entity
  public class CallCardAttribute implements Serializable, IEntity {
  private static final long serialVersionUID = 1L;
  
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;
  @Column(nullable = false)
  private String name;
  @Column(nullable = false)
  private String type;;
  @Column(nullable = false)
  @ManyToOne(optional = false)
  private Validator validator;
  
  public CallCardAttribute() {}
  ...
  </code></pre>
  
  <p>This class represents a single attribute of a CallCard. Since there can be many of them and the number can be different for any single one, I am storing the Attributes as a <code>Map&lt;Attribute, String&gt;</code>. To keep it in just one table, all the values are converted to Strings, regardless of the Java type in the application itself.</p>
  
  <p>But when loading them from the database, I need to cast them to the right type. So I store it as the <code>type</code> parameter in the <code>Attribute</code> class as a Class name string.</p>
  
  <p>I've figured out that I could use reflection to get an instance of the Class specified by the string and than fill it with the value.</p>
  
  <p>Like in this snippet:</p>
  
  <pre class="lang-java prettyprint-override"><code>Integer i = 17;
  String iVal = i.toString();
  String iType = i.getClass().getName();
  
  Object reVal = Class.forName(iType).newInstance();
  </code></pre>
  
  <p>But I need to cast <code>reVal</code> to the correct type, which can be any of String/Calendar/Integer/Double...</p>
  
  <p>Can this be done? And if so, how?</p>