I am trying to load a final class using the follwoing code
final ClassLoader myClassLoader = ClassLoader.getSystemClassLoader();
final String classNameToBeLoaded = "demo";
final Class myClass = myClassLoader.loadClass(classNameToBeLoaded);
// create a new instance
final Constructor cons = demo.class.getConstructor();......(1)
final Object whatInstance = cons.newInstance();
it’s returning me no such method exception…at 1.What the problem…?
If this fails, this means one of two things:
either there’s no default constructor or it’s not public (
class.getConstructor(...)only returns public constructors and if there was a public default constructor, you wouldn’t be doing this in the first place).You can solve the second problem by using
getDeclaredConstructor(...)instead ofgetConstructor(), it finds constructors with all visibilities:The first problem is tougher, obviously 🙂