我想知道是否有办法通过将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);
}
}
Run Code Online (Sandbox Code Playgroud)
一个用法示例:
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
}
Run Code Online (Sandbox Code Playgroud)
显然,Storage中的getValue()调用是一个伪代码调用,但它只是提供了我想做什么的想法.
无论如何都有一个getValue()调用,它将自动转换为存储在Storage类中的Class类型.同样,这个想法是Storage类知道它应该被强制转换为什么.或者,无论如何这可以完成吗?
StorageItem只是一个简单的例子.在这里,它只是存储一个int用于讨论目的.但是,它可能更复杂.
另一个用法示例是将Storage对象存储在列表中.
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));
Run Code Online (Sandbox Code Playgroud)
然后,可以通过以下方式访问它们.
//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();
Run Code Online (Sandbox Code Playgroud)
如果getValue()只返回一个Object,我必须总是手动转换为特定的Object.相反,如果我可以将转换类存储在Storage对象中,那么Storage有足够的信息来知道在getValue()调用中自动将Object转换为什么.
如果在Java中这是可行的,那就是我正在寻求的问题的答案.如果是这样,怎么样?
这会诀窍吗?需要更少的黑客攻击:
class Storage<T> {
private T value;
public Storage(T value) {
this.value = value;
}
public T getValue() {
return value;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3854 次 |
| 最近记录: |