简体   繁体   中英

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?

(Remeber I want ModuleM not 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM