kay
kay

Reputation: 481

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, i.e 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>)

Upvotes: 2

Views: 41

Answers (1)

ernest_k
ernest_k

Reputation: 45329

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.

Upvotes: 4

Related Questions