javaarraysargumentsclassloaderurlclassloader

Pass an Object Array in URL Class Loader - Java


I'm writing a java program which is pretty much modular, so very often its classes are loaded from a network share. I've found a solution for loading the classes. However it works with their arguments being int or String objects, but not a Object array a.k.a Object[]. I want it to be able to load classes which argument is only one and Object Array (in my head, it's more neat when passing more objects as argument). My edited for use with object array solution is down below, as well as the exception that throws. If anyone can help I would be very grateful.

public class LoadClassObjArrArg extends ClassLoader {

public LoadClassObjArrArg(String className, Object[] arg) {
    URL url;
    try {
        url = new URL("file:bin/cl/");
        URLClassLoader ucl = new URLClassLoader(new URL[]{url});
        Class<?> loadedClass = ucl.loadClass(className);

        try {
            Constructor constructor = loadedClass.getConstructor(Object[].class);
            constructor.newInstance(arg);
        } catch (Exception exception) {e.printStackTrace();
            Constructor constructor = loadedClass.getConstructor();
            constructor.newInstance();
        }


    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

In addition. Here is the stacktrace of the first exception in the inner try/catch block.

java.lang.IllegalArgumentException: wrong number of arguments
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at LoadClassObjArrArg.<init>(LoadClassObjArrArg.java:20)
at Saba.main(Saba.java:268)

and the second....

at LoadClassObjArrArg.<init>(LoadClassObjArrArg.java:20)
at Saba.main(Saba.java:268)"
java.lang.NoSuchMethodException: ScreenComponentParameters.<init>()
at java.base/java.lang.Class.getConstructor0(Class.java:3585)
at java.base/java.lang.Class.getConstructor(Class.java:2271)
at LoadClassObjArrArg.<init>(LoadClassObjArrArg.java:28)
at Saba.main(Saba.java:268)

Solution

  • For some reason it works when I convert to Object array to Object when calling the new instance.

    try {
                Constructor constructor = loadedClass.getConstructor(Object[].class);
                constructor.newInstance((Object)arg);
                
            } catch (Exception exception) {
                exception.printStackTrace();
                Constructor constructor = loadedClass.getConstructor();
                constructor.newInstance();
            }