[英]Infering generic type without creating new instance
private HashMap<Object, Object> attribute = new HashMap<>();
public <T> T attributeAs(Object key, T as){
Object ans = attribute.get(key);
return ans == null ? null : (T) ans;
}
method: 方法:
ModuleM m = (ModuleM) player.attribute.get("module_m");
Apart from that method, is there any way to return a type without creating a new class instance, ie this: 除了该方法之外,还有什么方法可以在不创建新类实例的情况下返回类型,即:
ModuleM m = person.attributeAs("module_m", new ModuleM());
Because when using the above you're creating a whole new instance and if ModuleM was a huge class with a lot of data, then that would affect processing power/speed correct? 因为使用上述方法时,您正在创建一个全新的实例,并且如果ModuleM是包含大量数据的庞大类,那么这会影响处理能力/速度是否正确?
(Remeber I want ModuleM not Class< ModuleM>) (记住我希望ModuleM不是Class <ModuleM>)
You don't need to send an instance: 您不需要发送实例:
public <T> T attributeAs(Object key){
Object ans = attribute.get(key);
return (T) ans;
}
The compiler will infer types based on the assignment on the invocation: 编译器将根据调用的分配来推断类型:
ModuleM attribute = person.attributeAs("module_m");
But of course, you might get class cast exceptions as your map supports <Object, Object>
entries, in the case where the actual instance is not compatible with the concrete target type. 但是,当然,在实际实例与具体目标类型不兼容的情况下,由于地图支持
<Object, Object>
条目,因此您可能会获得类强制转换异常。 That's because a call such as: 那是因为这样的呼叫:
String attribute = person.attributeAs("lastName") //probably OK
or 要么
String attribute = person.attributeAs("module_m") //probably problematic
would also be legal, but potentially incompatible. 也将是合法的,但可能不兼容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.