I have a data holder instance of String, integer, double, ... and I'm saving the data to (Oblect dataHolder
) and (Class dataHolderClass
). My question is how to cast back the dataHolder
to int
, String
...?
For instance I have the following data class:
class DataHolderClass {
private Object data;
private Class classData;
DataHolderClass(Object data, Class dataClass) {
this.data = data;
this.classData = dataClass;
}
Object getDataBack() {
return this.data;
}
Class getDataClassBack() {
return this.classData;
}
}
So how can I cast the data back knowing the dataClass
and having the data
? And here is some calling code (not sure if it is possible to do such kind of magic):
.....
public void foo(DataHolderClass input) {
Class inputClass = input.getDataClassBack();
Constructor constr = inputClass.getConstructor();
DataType recoveredData = constr.newInstance();
// ^------- the DataType is defined in inputClass but how can I get it?
recoveredData = (DataType) input.getDataBack();
...
}
Aucun commentaire:
Enregistrer un commentaire