简体   繁体   中英

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

I have two classes :

  1. MainClaz
  2. MyTest2

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

Since MyTest3 does not exist in this it will keep throwing ClassNotFoundException .

Now lets say ... I create new jar (Jar 2) containing class MyTest3 and copy this jar to class path 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 .

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 .

  1. Change package name of new jar to test2
  2. Add an import for MyTest3 :
import com.test2.MyTest3;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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