Integration of a third-party API into a Java application with conflicting dependencies

I am working on an existing application that has quite a few external JAR dependencies. I need to improve it to integrate with a third-party application that has an API. Unfortunately, the API is not good enough, and also has a large number of its own dependencies, some of which interfere with mine.

I believe that I should solve this with Classloaders, but I'm trying my best to structure them correctly.

To keep it simple, suppose I have myapp.jar with the hibernate3.jar dependency and vendor-api.jar with the hibernate2.jar dependency (and suppose they are incompatible).

My new piece of code will be in myapp.jar library (although it may be in a separate jar if that helps). Due to how the vendor API works, my new code should extend the class from vendor-api.jar library.

How can I structure Classloaders in such a way that anything inside vendor-api.jar refers only to its own dependencies, and everything on my side refers only to myapp.jar and dependencies?

Thanks Jon

+3
source share
3 answers

, , . , (AFAIK) "" API .

- () YMMV. .

class Orchestrator {
    URL[] otherAppClasspath = new URL[] { new URL("file:///vendor-api.jar"),
                                          new URL("file:///hibernate2.jar"),
                                          new URL("file:///code-extending-vendor-api.jar" };
    URLClassLoader otherAppLoader = new URLClassLoader(otherAppClasspath);

    URL[] yourAppClasspath = new URL[] { new URL("file:///myapp.jar"),
                                         new URL("file:///hibernate3.jar") };
    URLClassLoader yourAppLoader = new URLClassLoader(yourAppClasspath);

    public void start() {
        Method yourAppEntryPoint = yourAppLoader.findClass("com/company/Main").getMethod("start", new Class[] { Orchestrator.class } );
        yourAppEntryPoint.invoke(null, new Object[] { this });
    }

    public static void main(String[] args) {
        new Orchestrator().start();
    }

    // define some abstracted API here that can be called from your app
    // and calls down into classes in the other app
    public String getSomeResultFromOtherApp(int someArgument) {
        Method otherAppAPI = otherAppLoader.findClass("com/company/ExtendingAPIClass").getMethod("getSomeResult", new Class[] { Integer.class });
        return (String)otherAppAPI.invoke(null, new Object[] { someArgument });          
    }

}
+1

@fd answer , - , ..

, , ... API . , , , . .

, :

  • hibernate3.jar
  • hibernate2.jar
  • , JVM -.

, , .

0

Using OSGi can help you in the long run. Here is the implementation I'm trying to do http://felix.apache.org

0
source

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


All Articles