Loading jars at run-time
I am having comm.jar
and RXTXComm.jar
for serial communication. I have both of these jars in my class-path.
Now,开发者_StackOverflow社区 depending on a config parameter I should import appropriate jar at run-time. Please help me in resolving this issue.
You can instanciate a class loader and load the jar file. The standard classloaders have all the functionality you need.
Good tutorials/links to start:
- http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html
- http://www.javalobby.org/java/forums/t18345.html
Assuming they both have a superclass C
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Class.html#forName(java.lang.String) http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Class.html#newInstance()
Class a;
if(foo)
a = Class.forname("rxtx.somepackage.Someclass");
else
a = Class.forname("comm.somepackage.SomeOtherclass");
C c = a.newInstance();
CommDriver driver;
if (configA) {
driver = (CommDriver) Class.forName("rxtx.driver.package").newInstance();
} else {
driver = (CommDriver) Class.forName("com.sun.comm.Win32Driver").newInstance();
}
driver.initialize();
精彩评论