java - Casting Number to double primitive -
i'm trying access hashmap<string, number>
via reflection:
serializable obj; //here goes hashmap string name; ... return (double)obj.getclass().getdeclaredmethod("get", object.class).invoke(obj, name);
but far got casting error caused line above:
java.lang.classcastexception: java.lang.integer cannot cast java.lang.double
indeed, map value accessed key name
integer
.so i've changed line to:
return obj.getclass().getdeclaredmethod("get", number.class).invoke(obj, name).doublevalue();
but didn't work out either. got doublevalue()
underlined "undefined type object" (but why object if have number.class?).
i'm not sure casting rules i'm breaking. can someone, please, me if map entries have various number values (integer
, float
, double
) need method return double
value (primitive).
ps it's not duplicate. question more general. thank input. forgot invoke returns object.
the working code is:
return ((number)obj.getclass().getdeclaredmethod("get", object.class).invoke(obj, name)).doublevalue();
you have wrong assumption there relationship between class
object pass getdeclaredmethod
, return type of method.invoke
. class
objects pass getmethod
or getdeclaredmethod
describe parameter types of method, not return type. further, while may pass arguments of subtype of declared parameter type, have specify declared parameter type.
the parameter type of map.get
object
, invariably, have specify object.class
, regardless of actual key pass invoke
.
further, due type erasure, reflective return type object
, regardless of actual map
’s parametrization. not matters, method.invoke
’s declared return type object
, different method
instances may represent different methods.
so when have hashmap<string, number>
, can rely on returned objects number
instances, not double
instances. experienced, there integer
instances. have do, type-cast number
, followed invoking doublevalue()
:
return ((number)obj.getclass().getdeclaredmethod("get", object.class) .invoke(obj, name)).doublevalue();
that said, if know object implements map
interface, there no reason use reflection @ all:
return ((number)((map<?,?>)obj).get(name)).doublevalue();
does job more efficient.