-
if(Mod.class.isAssignableFrom( clazz )) { ... } // 1st
This should work, moreover it shouldn’t be possible for it to throw a ClassCastException.
Your code example seems to indicate that you might have an Exception block catching a whole host of Exceptions.
Are you sure this line is the source of the Exception?
-
if(clazz instanceof Mod) { ... } // 2nd
This is incorrect (clazz is always an instance of java.lang.Class); for your code example you’d want:
if(createdObject instanceof Mod) { ... }
However as previously mentioned, isAssignableFrom is the correct (more efficient & safer) approach as it performs the type check without requiring instantiation.
-
for( Class<?> interf : implInterfaces ) { // 3rd
if(interf.getName().equals( Mod.class.getName() )) { ... }
}
I’d advise against doing this; it’s fragile code.
I’m fairly sure it would break if you had something like:
Class A extends B
and then:
Class B implements Mod
Conclusion:
Constructor<?> constructor = clazz.getConstructor();
createdObject = (Mod)constructor.newInstance();
Each of these lines should be wrapped in individual Exception blocks, as they make assumptions about the subclasses of Mod that might not be true, and need to be handled appropriately.
Constructor<?> constructor = clazz.getConstructor();
Assumes that a no-args constructor exists.
createdObject = (Mod)constructor.newInstance();
Assumes that this constructor is accessible (public), and instantiable (not abstract).
Thus the cause of your problem might be a class that does implement the Mod interface, but fails because it lacks a public & no args constructor.
This failure (either a NoSuchMethodException, InstantiationException or IllegalAccessException) might then be getting caught by a blanket catch, and misinterpreted as a ClassCastException.
I’d suggest a more complete code listing so we can diagnose the problem without the speculative guessing I’ve made