jeudi 1 juin 2017

How to use reflection to invoke a static overloaded method in Java

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("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?





Aucun commentaire:

Enregistrer un commentaire