Dynamically loading classes from jar

I know that we can dynamically load classes using custom class loaders. But here my problem is that my class itself is dependent on other classes.

My task is to get the PigServer object. So I used the following code to load the PigServer class

_pigServerClass = _classLoader.loadClass("org.apache.pig.PigServer");

But here the PigServer class itself depends on many other classes.

Therefore, when I try to get an instance of the PigServer class, it shows the following errors

java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
java.lang.ClassNotFoundException:org.apache.log4j.AppenderSkeleton
 etc..

Can anyone tell how to solve this?

+5
source share
2 answers

How did you create your ClassLoader?

Have you specified another "parent" class loader to which you can delegate class loading?

0
source

, . , , "lib", , , :

    File libs = new File("lib");
    File[] jars = libs.listFiles(new FileFilter() {
        public boolean accept(File pathname) {
            return pathname.getName().toLowerCase().endsWith(".jar");
        }
    });

    URL[] urls = new URL[jars.length];
    for (int i=0; i<jars.length; i++) {
        urls[i] = jars[i].toURI().toURL();
    }
    ClassLoader uc = new URLClassLoader(urls,this.getClass().getClassLoader());


    Class<?> pigServerClz = Class.forName("org.apache.pig.PigServer", false, uc);
    Object pigServer = pigServerClz.newInstance();
    // etc...
+1

All Articles