简体   繁体   中英

Create class instance from class name

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?

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

If you don't want to use @OneToMany on the attribute collection you can use a JPA 2.0 ElementCollection.

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

You'll still end up with attribs in a separate table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM