Dynamically manage two jar files with the same pac

2019-06-26 04:18发布

I have two jar files from a client, one of which is used for a testing and another for final versions. Currently I put them in different folders and modify the library path when deploying our code, but it would be nice to be able to load both jar files and switch between them dynamically at runtime.

Is this possible?

4条回答
戒情不戒烟
2楼-- · 2019-06-26 04:26

You can always write your own ClassLoader and chain it with the standard ClassLoader.

http://download.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html

I used this method 10 years ago to load classes that were recieved via sockets and specified in an XML file (via sockets as well). My java program didn't know that the classes even existed before it got the XML file and the classes.

查看更多
Summer. ? 凉城
3楼-- · 2019-06-26 04:32

Using OSGi bundles you can do that. Take a look at http://blog.springsource.com/2008/02/18/creating-osgi-bundles/. Search for "multiple versions".

查看更多
家丑人穷心不美
4楼-- · 2019-06-26 04:43

If you use a build-tool like maven, you can define different jar files (dependencies) for different scopes (test vs production).

You may also use maven profiles to define different set of jar files/versions.

查看更多
干净又极端
5楼-- · 2019-06-26 04:49

justinjh,

chrisparker2000's suggestion looks to be the most feasible - You have to write a custom classloader, the only change that I can think of is something along the following lines: 1. For the client deliverable jars - say client.dev.jar and client.prod.jar, rename to a different extension and place these in the classpath. Rename to a different extension to prevent the container from loading the contents of the jar.

  1. Using the custom classloader, load the contents on demand, based on the solution offered by chrisparker2000, by placing a small facade on top of the client classes, say ClientClassFactory which based on the environment(dev/prod/anything else) would use the custom classloader to load from either client.dev.otherext or client.prod.otherext .
查看更多
登录 后发表回答