java - Dynamic cast an object to a specific class to use a function -


here piece of java code, , let's assume org.abc.test interface.

for (object obj : objectarray[]) {     if (obj instanceof org.abc.test) {         ((org.abc.test)obj).somemethod();     } } 

now suppose class org.abc.test passed dynamically string, code may this:

string classname = "org.abc.test"; class<?> clazz = class.forname(classname); ( object obj : objectarray[]) {     if (clazz.ininstance(obj)) {         obj = clazz.cast(obj);         obj.somemethod();     } } 

unfortunately statement obj.somemethod(); can't pass compilation, because compiler doesn't know specific class of object after casting.

so think statement should used:

class<? extends org.abc.test> clazz; 

can fix this? i'm new java reflection mechanism.


btw, found obj = clazz.cast(obj); not right way...

this doesn't work because obj still object compiler, after obj = clazz.cast(obj);. need explicit cast @peggy mentioned: ((org.abc.test)obj).somemethod();

if want make dynamic, can following:

if (clazz.isinstance(obj)) {     clazz.getmethod("somemethod").invoke(obj); } 

you don't need cast in case.


Comments