java - Get primitive value from Object extends Number? -
this question has answer here:
i trying make class can process subtracting, adding, updating number given type (anything extends number).
public class dynamicnumber<t extends number> { private t number; public dynamicnumber(t number) { this.number = number; } public void add(t number) { this.number += number; } public void subtract(t number) { this.number -= number; } } this won't work , throws following exception:
the operator += undefined argument type(s) (t, t)
this because can't use operator objects, , on primitive values.
my question how can primitive value of given object without knowing it's exact type, knowing extends number?
t extends object, never primitive. can use instanceof , cast object extends number. after - if object represents primitive - can use using auto unboxing or using explicit conversion. there no way around this.
Comments
Post a Comment