从类名创建类实例

时间:2012-01-18 18:04:31

标签: java reflection

我有这样的事情:

@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() {}
...

此类表示CallCard的单个属性。由于可以有许多这些数字,并且任何一个数字都可以不同,我将属性存储为Map<Attribute, String>。要将它保留在一个表中,所有值都将转换为字符串,而不管应用程序本身中的Java类型。

但是当从数据库加载它们时,我需要将它们转换为正确的类型。所以我将它作为type类中的Attribute参数存储为类名字符串。

我已经发现我可以使用反射来获取字符串指定的Class的实例,而不是用值填充它。

就像在这个代码段中一样:

Integer i = 17;
String iVal = i.toString();
String iType = i.getClass().getName();

Object reVal = Class.forName(iType).newInstance();

但我需要将reVal强制转换为正确的类型,可以是String / Calendar / Integer / Double ......

可以这样做吗?如果是这样,怎么样?

2 个答案:

答案 0 :(得分:0)

使用instanceof来确定要转换为: if(reVal instanceof String)result =(String)eval; ... 你需要一个单独的变量来强制转换为

答案 1 :(得分:0)

如果您不想在属性集合上使用@OneToMany,则可以使用JPA 2.0 ElementCollection。

http://en.wikibooks.org/wiki/Java_Persistence/ElementCollection

你仍然会在一张单独的表中找到attribs。