vendredi 19 mai 2017

Loading of imported classes of loaded classes using Reflection in Java

I am trying to load classes from a jar file. Basically, I want to call a method in a particular class in a package of that jar. The problem I am facing here is that after the class is successfully loaded from the jar and when I try to instantiate I get exception : ClassNotFound for classes imported in my class.

Here is the class which loads the class:

inputs: D:\Myjar.jar , com.vendor.epbroker.VNFLCMCommunicator

public Class<?> loadClass(String libPath, String pkgName) {
        LogManager.getLogger().info("Adding Class");

        File jarFile = null;
        try {
            jarFile = new File(libPath);
            URL fileURL = jarFile.toURI().toURL();
            String jarURL = "jar:" + fileURL + "!/";
            URL urls[] = { new URL(jarURL) };
            URLClassLoader ucl = new URLClassLoader(urls);
            Class<?> beanClass = ucl.loadClass(pkgName);
            ucl.close();

            return beanClass;
        } catch (Exception ex) {
            LogManager.getLogger().error("Given Library: " + libPath + " or Class name: " + pkgName + " is not Valid");
            LogManager.getLogger().error("Exception occurred : ", ex);
        }

        LogManager.getLogger().error("Class loading Error: Returning NULL");
        return null;
    }

The code snippet which receives this Class:

Object instance = classToLoad.newInstance();

                // To get the list of methods exist in the Class
Method[] listOfMethods = classToLoad.getMethods();

The following error is encountered:

SEVERE: Servlet.service() for servlet [spring] in context with path [/vnflcm] threw exception [Handler processing failed; nested exception is java.lang.NoClassDefFoundError: com/vendor/epbroker/exception/EPBrokerException] with root cause
java.lang.ClassNotFoundException: com.vendor.epbroker.exception.EPBrokerException
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671)
    at java.lang.Class.getConstructor0(Class.java:3075)

Any help would be appreciated?





Aucun commentaire:

Enregistrer un commentaire