I have something like this:
@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() {}
...
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 Map<Attribute, String>. To keep it in just one table, all the values are converted to Strings, regardless of the Java type in the application itself.
But when loading them from the database, I need to cast them to the right type. So I store it as the type parameter in the Attribute class as a Class name string.
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.
Like in this snippet:
Integer i = 17;
String iVal = i.toString();
String iType = i.getClass().getName();
Object reVal = Class.forName(iType).newInstance();
But I need to cast reVal to the correct type, which can be any of String/Calendar/Integer/Double...
Can this be done? And if so, how?