Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading classes dynamically from jar

I know that we can load classes dynamically by using custom class loaders. But here my problem is my Class itself is depends upon other classes

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

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

But here PigServer class itself is depends upon so many other classes.

So when i am trying to get instance of PigServer class then it is showing 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?

like image 269
Rajesh Barri Avatar asked Nov 13 '22 22:11

Rajesh Barri


1 Answers

There seems to be a misunderstanding. If you have all the jars required in a folder, say "lib", you can for example set up a class loader like this:

    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...
like image 86
gnomie Avatar answered Nov 15 '22 12:11

gnomie