user6299344
user6299344

Reputation:

Java casting object using Class

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();
    ...
}

Upvotes: 0

Views: 762

Answers (2)

Martin G
Martin G

Reputation: 329

If you can limit the options what DataObject can be, you can use an if/else sequence with the instanceof check like

 Integer castInt;
 Double castDbl;
 String castStr;  
 if (dataObject instanceof Integer) castInt = (Integer) dataObject;
 else if (dataObject instanceof Double) castDbl = (Double) dataObject;
 else if (dataObject instanceof Double) castStr = (String) dataObject;

That done you end up with the problem what cast field to use from thereon.

Upvotes: 0

Sergei Rybalkin
Sergei Rybalkin

Reputation: 3453

It is here since java 5 - generics.

class DataHolderClass<T> {
    T data;

    DataHolderClass(T data) { ... }
    T getData() { 
        return data;
    }
}

You have type safety out of box.

Upvotes: 2

Related Questions