I’m dynamically loading classes from jar files at runtime with a URLClassLoader. This works fine with this code:
Class<?> clazz = classLoader.loadClass( className );
Constructor<?> constructor = clazz.getConstructor();
createdObject = (Mod)constructor.newInstance();
But there is the problem of encountering a class that does not implement Mod and thus causes a class cast exception. I’m trying to get around this by checking before creating the object, if the loaded class implements Mod; I’ve tried:
if(Mod.class.isAssignableFrom( clazz )) { ... } // 1st
if(clazz instanceof Mod) { ... } // 2nd
for( Class<?> interf : implInterfaces ) { // 3rd
if(interf.getName().equals( Mod.class.getName() )) { ... }
}
But all of these throw their own ClassCastException.
Is there any way around this limitation?