java - What is the safe way to get the array class name at runtime? -
here example code requires obtaining class name of array unknown @ runtime:
//for calling methods declared similar // void method(string... values); //for primitive type have other overloads , following //is generic classes @suppresswarnings("unchecked") private static <t> void invokevaridic(method m, object host, t... values) throws illegalaccessexception, illegalargumentexception, invocationtargetexception, classnotfoundexception{ assert(values.length>0); //we assume users passes @ least 1 value class<? extends t[]> c = (class<? extends t[]>) class.forname("[l" + values[0].getclass().getname() + ";"); m.invoke(host, arrays.copyof(values, values.length,c)); }
since type erasure nature type of values
object[]
, cannot pass m.invoke
because requires string[]
. since forcing user pass @ least 1 value can use type of values[0]
construct new array.
i don't know t[].class
is.
i come above code depends on interpretation of array's name in byte code, safe? suggested way t[].class
?
you can't sure values in values
of type t
, because type-erased arrays subject heap pollution, , should prepared deal classcastexception
@ point cast. however, can array type particular object convoluted call array.newinstance
:
class<?> arrayclass = array.newinstance(values[0].getclass(), 1).getclass();
Comments
Post a Comment