0

Whenever dynamically loading a class using the URLClassLoader I get a NoSuchMethodException when trying to execute a method with a custom data type as a parameter. It finds methods with standard types like String and int but not the custom type.

Loaded Class:

public void execute(ProcessingData data){

    System.out.println("entered execute(ProcessingData data");

Calling Class:

URLClassLoader loader =
        new URLClassLoader(new URL[] {new File(alg.getPath()).toURI().toURL()}, AlgorithmLoader.class.getClassLoader());

    // Load class into memory
    Class<?> algClass = Class.forName(className, true, loader);
    logger.logInfo("Loaded class. Attempting to invoke execute(data) on aircraft: "+ data.getFlightData().getAircraftId());
    Method processMethod = null;

    try {
      Object obj = algClass.newInstance();
      processMethod = algClass.getDeclaredMethod("execute", ProcessingData.class);
      processMethod.invoke(obj, data);
    } catch (final NoSuchMethodException exception) {
      logger.logInfo(exception.toString());
    }
    loader.close();

2 Answers 2

0

You're invoking the method without any object (null parameter of invoke). This means that the method will be expected to be static.

If your method is not static then you first need to create an instance of the type algClass using getConstructors() and pass that object to the first parameter of the invoke call.

2
  • You're right and I updated the code in my question. I simply missed type the code block when copying it over. Its fixed now but still has the same error.
    – Ben
    Apr 10, 2020 at 20:04
  • Does it crash at the invoke line or before that? Can you maybe post the stacktrace? Apr 11, 2020 at 4:43
0

My guess would be that your UrlClassLoader gets ProcessingData loaded by different class loader than your executing code in the posted snippet. Recall that classes loaded via different class loaders are different classes as far as JVM is concerned.

3
  • I think you might be right. How could I make sure they are the same?
    – Ben
    Apr 10, 2020 at 22:03
  • @Ben that is a rather complex subject. In short you must ensure that you do not load same class (from same or different jars) with more than one class loader. It is hard to say more without much more details about how are your loaders organized (from your code I can see that your URLClassLoader uses ClassLoader of AlgorithmLoader class as its parent, implying you have non-trivial hierarchy of class loaders).
    – suff
    Apr 12, 2020 at 16:20
  • 1
    @Ben as a first attempt, use ProcessingData.class.getClassLoader() instead of AlgorithmLoader.class.getClassLoader() as parent loader…
    – Holger
    Apr 15, 2020 at 10:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.