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();
...
}
dataClass.cast(data)? But it doesn't sound like you'd need this. If your caller already knows to put the result into the variable of typeDataType, why would you need to cast reflectively? If it doesn't know theDataTypetype ahead of time, than it needs to store it intoObjectvariable anyway, so why the cast? You can't choose a variable type at runtime.