Classloader and loading a class whose location does not equal its package

855 views Asked by At

I'd like to be able to load a class(es) from a known directory whenever a compiled .class file appears in that particular directory. However the I'd like the .class to be loaded regardless of what the package decleration is in its .java file. For example I have this class which I wish to load:

package com.javaloading.test;

public class SomeClassInPackage {
    private String name = "The name of this Class is SomeClass.";
    public String getName(){
            return name;
    }

}

And it is in the package com.javaloading.test. I then want to load it using this class:

public class GetPackage {

    public static void main(String[] args){
            new GetPackage().loadMyClass();
    }

    public void loadMyClass(){
            // Get the current class loader
            ClassLoader cl = getClass().getClassLoader();
            try {
                    Object o = cl.loadClass("SomeClassInPackage");
                    System.out.println("Class loaded!");
            } catch (ClassNotFoundException ex){
                    System.out.println("Could not load class");
            }
    }
}

If I put the .class files of both the above Classes into the same directory and run GetPackage it results in the error

Exception in thread "main" java.lang.NoClassDefFoundError: SomeClassInPackage (wrong name: com/javaloading/test/SomeClassInPackage

I need to be able to load a class (from a file) regardless of it's declared package and without having to actually know its package. I would then examine the loaded class for its package information. Is this possible using the System ClassLoader or a custom ClassLoader or is it impossible without having knowledge of the package structure? If it's possible any advice is appreciated.

1

There are 1 answers

4
user2880879 On

It is impossible to load the class without its respective package structure, means if you want to load the class then it must be placed in the folder that is correspond to its packages name or that class is in a jar file but in same folder structure.

But lets say you want to load the classes which is external means not in the class path where this program gets executed from and you want to load it in current class loader during execution. Refer to this link How to load the classes at runtime. This will also gives answer to your next question where you want to load the classes which is selected by the program based on its name or package.