Magic Cast - Convert String to various object types

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 of code, in the specific situation, I get a String "10/01/2018", and need to convert it to Date and / or other types (Integer, String , ...) as follows:

//Cast Magico?
minhaData = (reportParam.getClasse()) "10/01/2018";
    
asked by anonymous 26.01.2018 / 17:05

1 answer

2

Using reflection, you can try instantiating a java.lang.reflect.Constructor , passing String.class as a parameter to it. BUT, 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" );
    
26.01.2018 / 17:33