5

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?

2 Answers 2

1

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...
0

How you created your ClassLoader?

Did you specified another "parent" classloader, on wich classloading can be delegated?

7
  • I have created class loader ..its take class path and returns _customClassLoader = new URLClassLoader(urls,PigClassLoader.class.getClassLoader()); Sep 13, 2012 at 6:58
  • that to my class loader is working fine. Thats y it didnt show class not found exception for PigServer Class Sep 13, 2012 at 7:04
  • Are you're sure, that commons-logging and log4j are in the classpath?
    – Mirko
    Sep 13, 2012 at 7:09
  • No . I want it as dynamic loading. All those classes are in Pig.jar;I am passing that pig.jar path to my custom classLoader as class path. Sep 13, 2012 at 7:45
  • 2
    I'm sorry, but I think that I dont understand your what your problem is. In Standard: a class will loaded on demand when it is needed. you only have to configure the classpath. So if you're implementing it by yourself you'll just get the benifit of less classpath-configuration. So why you not add the jars, required at runtime to the Standard-ClassLoader? See: stackoverflow.com/questions/1010919/…
    – Mirko
    Sep 13, 2012 at 7:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.