Java - creating a library and importing optional

I have a library that I use in a Java application - it is important for certain functions, but not required. This means that if the JAR file does not exist, the program continues to work without problems. I would like to open the source version of my program, but I cannot include this library, which is necessary for compiling the source code, since I have many import statements for using the API. I do not want to support two sets of code. What is the best way to remove the physical jar file from the open source version, but save the code for support, where other people can still compile it?

+4
source share
3 answers

a typical approach is to define a wrapper API (for example, interfaces) and include these interfaces in open source, and then provide configuration options where you can specify class names of classes that implement certain interfaces.

You import APIs instead of importing classes directly into your open source code. This way you open the API search, but do not implement parts that you do not want to open, or you cannot open the source.

There are many examples, but check out the JDBC (interfaces) and JDBC (implementation classes) APIs for starters.

+3
source

I pretty much printed the same thing as smallworld with one add-on. If this API was needed, you can use a project build tool like Maven to handle dependencies on your project. If someone checks this from the source control using pom, they can load the dependencies for themselves, and you do not need to include them in the source repo.

+3
source

There are probably several ways to fix this, here are a couple I can think of:

  • If you have only a few methods that need to be called in a third-party library, you can use reflection to call these methods. It creates really verbose code that is hard to read.

  • If you do not use too many APIs in a third-party library, you can also create a separate JAR file containing only the functional wrapper of classes in the library (only types with the same names and methods with the same signatures). Then you can use this JAR for distribution and compilation. At run time, you replace it with a real JAR if one is available.

  • The most common way, probably, is to simply create a wrapper API in a separate module / project for code that depends on a third-party library, and possibly distribute a pre-built JAR. This may run counter to your desire not to support two sets of code, but it may turn out to be a better and less painful solution in the long run.

+3
source

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


All Articles