I'm wondering if there is a way to Auto Cast an Object to some type by storing the Class type along with the object? I thought this was possible with Java, but maybe not.
For example:
class StorageItem
{
private int itemcount;
StorageItem(int itemcount)
{
this.itemcount = itemcount;
}
int getItemCount()
{
return itemcount;
}
}
class Storage
{
private Class clazz;
private Object value;
public Storage(Class clazz, Object value)
{
this.clazz = clazz;
this.value = value;
}
//Is there a way such a call can be created to automatically cast
//the object to the class type and return that cast type in a
//generic way. The idea being that Storage knows what it should
//already be cast to. Is this possible?
public T getValue()
{
return clazz.cast(value);
}
}
A usage example:
public static void main(String[] args)
{
//Create storage item
Storage storage = new Storage(StorageItem.class, new StorageItem(1234));
//The call to getValue() will automatically cast to the Class passed
//into Storage.
int itemcount = storage.getValue().getItemCount(); //returns 1234
}
Obviously the getValue() call in Storage is a pseudocode call, but it's just there to provide the idea as to what I would like to do.
Is there anyway to have a getValue() call that will Auto cast to the Class typed stored in the Storage class. Again, the idea is that the Storage class knows what it should be cast to. Or is there anyway this can be done at all?
StorageItem is just one simple example. Here, it just stores an int for discussion purposes. However, it could be more complex.
Another usage example, would be storing the Storage object in a list.
List<Storage> row = new ArrayList<Storage>();
row.add(new Storage(StorageItem.class, 1234));
row.add(new Storage(String.class, "Jason"));
row.add(new Storage(Integer.class, 30));
row.add(new Storage(Double.class, 12.7));
Then, these can be accessed in the following way.
//calls StorageItem's getItemCount() method
row.get(0).getValue().getItemCount(); //returns 1234
//calls String's length() method
row.get(1).getValue().length(); //returns 5
//calls Integer's intValue() method
row.get(2).getValue().intValue();
//calls Integer's doubleValue() method
row.get(3).getValue().doubleValue();
If getValue() only ever returned an Object, I would have to always cast to the specific Object manually. Instead, if I can store the cast class inside the Storage object, then Storage has enough information to know what to automatically cast the Object to on the getValue() call.
If this is doable in Java is the answer to the question I'm seeking. And if so, how?
Storage storage = new Storage(StorageItem.class, new StorageItem(1234));instead ofStorageItem storageItem = new StorageItem(1234);?class Storage { ...andprivate Object valuetoclass Storage<T> { ...resp.private T value;and you're all set.row.get(0)is an instance of a "StorageItem-bearing"Storage, rather than a "String-bearing"Storage.