Search code examples
javainheritanceclassloaderextending-classes

Extending Java Third Party APIs


Its more likely a subjective question. I wanted to create a sub class of a third party API to customize the behavior, but the problem is one of the method in API class is having default access specifier, and I am not allowed to override as my sub class is not in same package.

However, if I want a solution, I can put my subclass in same package as of API class and extend the method which has default access specifier. Third party jar file is licensed under a permissive X11 type license (which is similar to MIT License)

I am looking for answer for below queries

  1. Is that legal to create subclass outside third party jar( different jar file) but maintaining similar package conversion?

  2. Any known issue with this approach (even though same package name, I kept in two jars)( i just tested with stand alone unit test)

  3. How Class loaders of app servers behave in such scenario ( which jar file will be loaded first)

Apologies if my query(1) related to license is not applicable here.

Thanks in advance.


Solution

  • For (1): The X11 license basically says you can do anything with the software as long as you credit the authors and don't sue them for breach of warranty. There is nothing illegal about what you suggest.

    While what you suggest should work, it's hackish. The problem is that the third-party library is using an overly strict access specification for part of its API. The best way would be to submit a patch to the open-source project.

    Your patch should simply specifies the method in question as protected instead of package-private, which would allow it to be called by subclasses (as well as other classes in the library's package, since protected includes package-private access). That way, it would also help other users of the library extend the class.