【发布时间】:2016-09-18 22:04:26
【问题描述】:
我想知道是否有一种方法可以通过将 Class 类型与对象一起存储来将对象自动转换为某种类型?我认为这在 Java 中是可能的,但也许不是。
例如:
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);
}
}
一个用法示例:
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
}
显然,Storage 中的 getValue() 调用是一个伪代码调用,但它只是为了提供关于我想要做什么的想法。
是否有一个 getValue() 调用会自动转换为存储在 Storage 类中的类。同样,这个想法是 Storage 类知道它应该转换成什么。或者无论如何这都可以做到?
StorageItem 只是一个简单的例子。在这里,它只是存储一个 int 用于讨论目的。但是,它可能会更复杂。
另一个使用示例,将存储对象存储在列表中。
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));
然后,可以通过以下方式访问它们。
//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();
如果 getValue() 只返回一个对象,我将不得不手动强制转换为特定对象。相反,如果我可以将转换类存储在 Storage 对象中,那么 Storage 就有足够的信息来知道在 getValue() 调用上自动将 Object 转换为什么。
如果这在 Java 中是可行的,那就是我正在寻找的问题的答案。如果是这样,怎么办?
【问题讨论】:
-
为什么不使用简单的泛型类?
-
为什么是
Storage storage = new Storage(StorageItem.class, new StorageItem(1234));而不是StorageItem storageItem = new StorageItem(1234);? -
将
class Storage { ...和private Object value分别更改为class Storage<T> { ...。private T value;一切就绪。 -
如果可以自动为我完成,我想避免直接转换 Object 类型。由于 Storage 也知道它应该自己转换哪个类,所以我不确定是否可以将一个方法写入 Auto Cast 到传递给 Storage 对象的 Class。请在上面查看我最近的更新。
-
您在这里要求做的事情无法完成:编译器无法知道
row.get(0)是“StorageItem-bearing”Storage的一个实例,而不是“String-bearing”Storage。