1

I am trying to build a microservice system in Java. For the services themselves, I created a class Service which all Services extend. An example service would look like this:

package me.test;

public class TestService extends Service {

    public TestService() {
        System.out.println("It works!");
    }

    public static void execute(String s) {
        System.out.println(s);
    }

}

My service loader class looks somewhat like this:

package me.microservices.app;

public class ServiceLoader {

    public ServiceLoader() {
        List<File> files = Arrays.asList(new File(getDataFolder().getPath() + "/services").listFiles());
        URL[] urls = new URL[files.size()];
        for (int i = 0; i < files.size(); i++) {
            try {
                urls[i] = files.get(i).toURI().toURL();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        URLClassLoader serviceClassLoader = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader());

        Class<?> testServiceClass = Class.forName("me.test.TestService", false, serviceClassLoader);
        testServiceClass.getMethod("execute", String.class).invoke(this, "This is a certified hood classic!!!");
    }

}

The Service class is part of my microservices app at me.microservices.api.Service.

When I execute my code withour the class TestService extending Service, my code runs fine and prints all the text I want it to. But for some reason when I try to make my TestService a subclass of Service, I get a NoClassDefFoundError.

I've already tried to use the Thread.currentThread().getContextClassLoader() when initializing my URLClassLoader but that makes no difference. I also tried including my API into the build TestService.jar, without any difference as well.

One thing, that I might mention: I am trying do develop this as part of a Bukkit/SpigotMC Plugin. This may be the cause to why the program doesn't know the Service class. In this case, I would need to use a class loader at the microservices.jar plugin classpath but I have no idea how to do that.

DeveloperTK
  • 112
  • 2
  • 9

1 Answers1

1

I found out the solution to the problem:

Since I am developing a SpigotMC Plugin, the classpath of the Thread.currentThread().getContextClassLoader() is the classpath of my SpigotMC Server. In order to load classes from my plugin, I need to use PluginMainClass.class.getClassLoader().

I hope that I could help somebody with this post ;-)

DeveloperTK
  • 112
  • 2
  • 9