Search code examples
javaclassclassloaderclassnotfoundexception

Import class in Java via absolute path


I've been trying to import a .class via absolute path while code is running and I don't know how to do it.

I found a way to import a class when it's already in project's build path by Class.forName();but I need to find a way to load a class that is not in build path.

The goal is:

  1. User is able to upload his own .class file which is then saved locally to a specific folder and path is saved in database
  2. Via GUI user can select this file to be used while code is running
  3. My code should load a class via this given absolute path while code is running

The problem is with 3rd point because I don't know if it is possible to load a class while code is running.

I've tried using URLClassLoader but I'm getting ClassNotFound error.

EDIT:

Basically, I have this static function which should return Class by it's name, but urlClassLoader.loadClass() throws error.

Name of a file is J48.class so for className argument I've tried using "J48", "J48.class" but none work.

Additionaly I've tried setting folder classifiers to build path and setting argument to "weka.classifiers.trees.J48" which is full path with package to this class (package structure is weka.classifiers.trees).

`public static Class getClassByName(String className) throws MalformedURLException, ClassNotFoundException 
    {
        URLClassLoader urlClassLoader = URLClassLoader.newInstance(new URL[] {
                   new URL("file:///D:\\xampp\\htdocs\\prog-ing\\classifiers\\")
        });

        Class class = urlClassLoader.loadClass(className);

        return class;
    }`

Solution

  • Okay so after thinking a bit, I only got to the one solution (still not satisfied with it) which is following:

    every class that needs to be uploaded by user is saved into workspace of this project and therefore I am able to get class using Class.forName(); pointing out this "folder" of uploaded classes, in my case: Class.forName("classifiers.className");