简体   繁体   English

如何从添加到Java中的类路径的新Jar中自动加载类?

[英]How to load classes automatically from new Jar added to Class path in java?

I have two classes : 我有两节课:

  1. MainClaz
  2. MyTest2

In MainClaz , MainClaz

public class MainClaz {

    public static void main(String[] args) throws InterruptedException {
        while (true) {
            try {

                Class aClass = Class.forName("com.test.MyTest2");
                Object t =  aClass.newInstance();
            } catch (Exception e) {
                System.out.println("Exception For MyTest2 ");
            }
            Thread.sleep(10000);
            try {
                Class aClass = Class.forName("com.test.MyTest3");
                Object t =  aClass.newInstance();
            } catch (Exception e) {
                System.out.println("Exception For MyTest3 ");
                e.printStackTrace();
            }
        }
    }
}

I have packaged both class in a jar (Jar 1) and put it to the class path . 我将两个类都打包在一个jar中(Jar 1),并将其放在类路径中。

Since MyTest3 does not exist in this it will keep throwing ClassNotFoundException . 由于MyTest3不存在,因此它将继续抛出ClassNotFoundException

Now lets say ... I create new jar (Jar 2) containing class MyTest3 and copy this jar to class path Folder. 现在说...我创建了一个包含类MyTest3新jar(Jar 2),并将此jar复制到类路径Folder。

Since I have put MyTest3 class in different new jar in class , It should find MyTest3 in class path on-wards but it is throwing ClassNotFoundException . 由于我已经将MyTest3类放在类中的其他新jar中,因此应该在类路径中继续查找MyTest3 ,但是会抛出ClassNotFoundException

How can i make this to work ? 我如何使它工作?

Adding More information to Requirement : 在需求中添加更多信息:

As of now class names are hard coded . 到目前为止,类名已经过硬编码。 But they would be read from external source (Let's say some database ). 但是它们将从外部源(比如说一些数据库)中读取。 But I want is , add new class in new jar in class path , add entry of fully qualified name of class in database , so that in next iteration of loop program can dynamically load class . 但是我想要的是,在类路径中的新jar中添加新类,在数据库中添加类的全限定名条目,以便在循环程序的下一次迭代中可以动态加载类。

  1. Change package name of new jar to test2 将新罐子的包名称更改为test2
  2. Add an import for MyTest3 : MyTest3添加导入:
import com.test2.MyTest3;

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

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