Dynamically manage two jar files with the same package and class names

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

Is it possible?

+4
source share
4 answers

You can always write your own ClassLoader and associate it with a 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 received through sockets and specified in an XML file (through sockets). My java program did not know that classes even existed before it received the XML file and classes.

+6
source

Using OSGi packages, you can do this. Take a look at http://blog.springsource.com/2008/02/18/creating-osgi-bundles/ . Find "multiple versions."

+2
source

justinjh,

Sentence

chrisparker2000 looks the most feasible - you need to write your own class loader, the only change I can think of is something like the following lines: 1. For client containers, say client.dev.jar and client.prod.jar, rename into another extension and put them in the classpath. Rename to another extension so that the container does not load the contents of the container.

  • Using a custom class loader, load content on demand based on the solution offered by chrisparker2000, placing a small facade on top of client classes, say ClientClassFactory, which based on the environment (dev / prod / anything else) will use a custom class loader to load from the client file. dev.otherext or client.prod.otherext.
+1
source

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

You can also use maven profiles to define different sets of jar files / versions.

+1
source

Source: https://habr.com/ru/post/1303698/


All Articles