Question

I tried dynamic loading of classes in a simple program and intrestingly when ever i try dynamic loading of classes with simple name it fails with classnotfoundexception. this happends only if the classes are under a package other than default package.

But when i specify the full path name, the dynamic loading succeeds. The class being loaded is in the same package as the Main class.

File Main.java:

public class Main {

    public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {                  
        System.out.println(Class.forName("m"));
    }
}

class m extends Main{
}
Was it helpful?

Solution

No, Class.forName always needs the package-qualified class name. From the parameter documentation:

className - the fully qualified name of the desired class.

The package of the calling code is irrelevant.

OTHER TIPS

You have to put fully qualified class name for the Class here

such as System.out.println(Class.forName("com.sample.M"));

assuming

com.sample is your class package name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top