简体   繁体   中英

How to restrict the usage of a Java public class outside of its Jar?

I'd like to be able to annotate a public class/interface in Java as @NonPublic , which would mean This interface is only to be used within this project, it is not part of the public API that this project exports .

This is common for projects that are composed of several jar files. Not all public classes/interfaces are meant to really be public outside of your jar.

Do you know of any tool/framework/plugin that does this?

IMHO the package system in Java is one of the most broken things that exist.

I'm not familiar with any standard Java-level mechanism to do that, although it is probably easy to write a tool or compiler extension that will enforce it.

However, if you are using OSGi (Eclipse is written that way), one of its advantages is a system for specifying better package and module level restrictions.

Without OSGi another common practice is the separate API from implementation.

You could separate classes required during compile time from the ones which are required during runtime. To prevent users of your library to have dependencies to implementation details.

myLibAPI.jar   
myLibImpl.jar

OSGi Bundle is the solution.

If you want to convert you Jar into an Eclipse Plug-in, you can use Eclipse RCP release. Right click on your project : Configure -> Convert to plug-in projects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM