vendredi 17 juillet 2015

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

Here is a piece of java code, and let's assume it's called org.abc. Test is an interface.

for (Object obj : objectArray[]) {
    if (obj instanceof org.abc.Test) {
        ((org.abc.Test)obj).someMethod();
    }
}

Now suggest class org.abc. Test is passed dynamically as a String, the code may be like this:

String className = "org.abc.Test";
Class<?> clazz = Class.forName(className);
for ( Object obj : objectArray[]) {
    if (clazz.inInstance(obj)) {
        obj = clazz.cast(obj);
        obj.someMethod();
    }
}

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

So I think some statement like this should be used:

Class<? extends org.abc.Test> clazz;

Can somebody help fix this? I'm just new to java reflection mechanism.





Aucun commentaire:

Enregistrer un commentaire