0

I want to use Java Reflection to invoke a method from a class which I have in my classpath via URLClassLoader from a jar file.

Class I want to access from the Jar file:

package org.example;

public final class Sample {

    private Sample() {} //disallow outside instantiation

    public static void initialize(String a) {
        Sample.initialize(a, "some string", "some other string")
    }
    public static void initialize(String a, String b, String c) {
        //some logic...
    }

    // ...
}

Here is how I am trying to access the above class from a top level Main class in . a class called Test:

public static void main(String[] args) throws Exception {
    final URLClassLoader v1Loader = URLClassLoader.newInstance( new URL[] { new File("./jar/sample.jar").toURI().toURL()} );
    final Class<?> engineClassV1 = v1Loader.loadClass("org.example.Sample");
    Method initMethod1 = engineClassV1.getMethod("initialize", String.class);.........(25)
}

I get an exception on line 25:

Exception in thread "main" java.lang.NoClassDefFoundError: org/example/services/common/exception/ServiceException
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
    at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
    at java.lang.Class.getMethod0(Class.java:3018)
    at java.lang.Class.getMethod(Class.java:1784)
    at org.sample.Test.main(Test.java:25)

What am I doing wrong? How to access the overloaded static initialize method with the single String parameter?

mosawi
  • 1,283
  • 5
  • 25
  • 48
  • Are you sure you have both sample.jar and your main class in the *same* directory? If not, use absolute paths as parameters. – DarkCygnus Jun 01 '17 at 22:47
  • They are not, but I edited my question to reflect this. sample.jar is located in a folder called jar in the root of the project along with the src folder and the pom.xml file. – mosawi Jun 01 '17 at 22:50
  • 2
    The error is complaining that it can't find `org/example/services/common/exception/ServiceException`, so the issue isn't with the way you are using `getMethod`. – Radiodef Jun 01 '17 at 22:52

0 Answers0