根据预定义的 API 限制对类和方法的访问 [英] Restrict access to classes and methods according to a predefined API

查看:24
本文介绍了根据预定义的 API 限制对类和方法的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Java 项目,其中包含多个包和每个包中的多个类.我希望这个项目被用作一个库(在这种情况下最好说是框架),提供某些功能.该框架将被其他应用程序(在不同的 Eclipse 项目中)使用.

I have a Java project with multiple packages and multiple classes in each package. I want this project to be used as a library (better say framework in this case), offering certain functionalities. The framework will be used by other application (in a different Eclipse project).

我如何指定可供其他应用程序使用的类和方法?我只希望一些类/方法成为 API 的一部分.其余的实现代码应该对用户隐藏.

How can I specify the classes and methods that I want to be available for other applications? I only want a few classes/methods to be part of the API. The rest of the implementated code should be hidden for the users.

PD:我的意思不是如何设计 API,而是如何组织代码或我应该使用哪些访问修饰符.

PD: I don´t mean how to design the API, but how to organize the code or which access modifiers should I use.

推荐答案

好吧,除非您将所有代码放在一个包中,否则您将需要公开实现中包之间共享的任何内容.

Well, unless you put all the code in one package, you're going to need to make public anything that gets shared between packages in your implementation.

通常按照惯例解决这个问题的方法是:仅提供 API 类的文档,并指定您的 JAR 中的任何其他类不受支持并且可能随时更改.这就是 Sun 对 java 所做的——API 在两个独立的包结构下提供,java.whatever 和 com.sun.whatever.com.sun 不受支持或记录,使用这些类的风险由您自己承担.

Typically the way this problem is solved is by convention: provide documentation only for the API classes, and specify that any other classes in your JAR are not supported and may change at any time. This is what Sun did with java - the API ships under two separate package structures, java.whatever and com.sun.whatever. com.sun is not supported or documented, and you use those classes at your own risk.

一些 API 提供商还喜欢提供两个单独的 JAR,其中一个是明确的 API,另一个是明确的支持/实现.这允许客户端只对 API JAR 具有编译时依赖关系,但对两者都有运行时依赖关系.

Some API providers also like to ship two separate JARs, one of which is explicitly API and the other is explicitly support/implementation. This allows clients to only have a compile-time dependency on the API JAR, but a runtime dependency on both.

您还应该强烈考虑密封您的 JAR,以防止客户端将类放入您正在使用的相同包中并访问您的受保护或包保护(默认)成员.

You should also strongly consider sealing your JAR(s) to prevent clients from putting classes in the same packages you're using and access your protected or package protected (default) members.

这篇关于根据预定义的 API 限制对类和方法的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆