从类名创建类实例
我有这样的东西:
@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
。为了将其保留在一张表中,所有值都将转换为字符串,无论应用程序本身的 Java 类型如何。
但是当从数据库加载它们时,我需要将它们转换为正确的类型。因此,我将其作为类名称字符串存储在 Attribute
类中的 type
参数中。
我发现我可以使用反射来获取字符串指定的类的实例,然后用值填充它。
就像这个片段一样:
Integer i = 17;
String iVal = i.toString();
String iType = i.getClass().getName();
Object reVal = Class.forName(iType).newInstance();
但是我需要将 reVal
转换为正确的类型,可以是 String/Calendar/Integer/Double 中的任何类型...
可以这样做吗?如果是这样,怎么办?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

使用instanceof来确定要转换到哪个:
if (reVal instanceof String) 结果 = (String) eval;
...
您需要每种类型都有一个单独的变量来转换为
use instanceof to determine which to cast to:
if (reVal instanceof String) result = (String) eval;
...
You'll need a separate variable of each type to cast to