Magic Cast - Convert String to Various Object Types

Asked

Viewed 34 times

0

Class:

@Entity
public class ReportParam extends AbstractModel implements JRParameter {

@Column
private String nome;

@Column
private String descricao;

@Column
private Class<?> classe;

The goal:

Use the instantiated attribute reportParam.getClasse() as cast in a line code, in the specific situation, I get a "10/01/2018" String, and I need to convert it to Date and/or other types (Integer, String,...) as follows:

//Cast Magico?
minhaData = (reportParam.getClasse()) "10/01/2018";

1 answer

2


Using Reflection, you can try instantiating a java.lang.reflect.Constructor, passing by String.class as parameter for it. HOWEVER, the object you want to instantiate must have a constructor that receives String, otherwise an exception will occur.

Constructor c = reportParam.getClasse().getConstructor( String.class );
minhaData = c.newInstance( "10/01/2018" );

Browser other questions tagged

You are not signed in. Login or sign up in order to post.