简体   繁体   English

从jar动态加载类

[英]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 我的任务是获取PigServer对象。所以我使用以下代码加载PigServer类

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

But here PigServer class itself is depends upon so many other classes. 但是这里PigServer类本身依赖于很多其他类。

So when i am trying to get instance of PigServer class then it is showing following errors 因此,当我试图获取PigServer类的实例时,它显示以下错误

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

Can anyone tell how to solve this? 有谁能说出如何解决这个问题?

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: 如果你有一个文件夹中所需的所有jar,比如“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...

How you created your ClassLoader? 你是如何创建ClassLoader的?

Did you specified another "parent" classloader, on wich classloading can be delegated? 您是否指定了另一个“父”类加载器,可以委托加载类加载吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM