What should be the file path I use when instantiating a URL for a java URLClassLoader?

127 views Asked by At

I'm attempting to use a URLClassLoader am having some trouble. I'm exclusively running into a ClassNotFoundException at runtime and I'm wondering if the issue is my file path I'm using for the jar file I'm attempting to load in.

I am trying to follow this tutorial exactly and I'm assuming it works so the only error must be the file path I'm using.

The file path of the jar file on my pc is:

C:\xxxx\xxxx\IdeaProjects\TesterforURL\src\com\jcg

The line of code I'm using to find it is:

URL[] classLoaderUrls = new URL[]{new URL("file://C:/xxx/xxxx//IdeaProjects/TesterforURL/src/com/jcg/classloader.jar")};

This is the code within the jar file:

package com.jcg;


public class Bean {

    public void sayHello() {
        System.out.println("Hello from loaded Bean class !!!");
    }

}

and this is the full code in my project:

package com.jcg;

import java.lang.reflect.Constructor;

import java.lang.reflect.Method;

import java.net.URL;

import java.net.URLClassLoader;



public class URLClassLoaderTest {


    public static void main(String[] args) throws Exception {

        // Getting the jar URL which contains target class
        URL[] classLoaderUrls = new URL[]{new URL("file://C:/xxxx/xxxx//IdeaProjects/TesterforURL/src/com/jcg/classloader.jar")};

        // Create a new URLClassLoader
        URLClassLoader urlClassLoader = new URLClassLoader(classLoaderUrls); 

        // Load the target class
        Class<?> beanClass = urlClassLoader.loadClass("com.jcg.Bean");

        // Create a new instance from the loaded class
        Constructor<?> constructor = beanClass.getConstructor();
        Object beanObj = constructor.newInstance();

        // Getting a method from the loaded class and invoke it
        Method method = beanClass.getMethod("sayHello");
        method.invoke(beanObj);

    }

}

Is the issue my filepath or is it some other problem with the code?

Thanks in advance and apologies if this is formatted or summarized incorrectly, this is my first question :)

1

There are 1 answers

1
Jude Snee On

Don't worry I've sorted it, it had to be in the format

file:C:\xxx\URLUsingThingy\src\com\jcg\examples\URLExample.jar