包装和可见性

我正在制作一个 SDK,我正在尝试将类分离到不同的包中,这些类使用其他一些共享类.问题是如果我公开共享课程,每个人都可以看到它们,而不仅仅是我的课程.使它们只能由我的应用程序访问的正确方法是什么?

I'm making an SDK and I'm trying to separate classes to different packages, those classes use some other shared classes. The issue is if I made the shared classes public everyone will be able to see them, not only my classes. What's the right way to make them only accessible by my application?

例子:

包装一个我的班级1

包 b我的班级2

包c公共MySharedClass

Package c public MySharedClass

因为 c 是公共的 MySharedClass 将能够访问它,但问题是它也将对世界可见,我该如何防止这种情况发生?

Because c is public MySharedClass will be able to access it, but the issue is that it will also will be visible to the world, how could I prevent that?

推荐答案

不平凡:

共享类可以由一组一般可访问的接口定义.实际的实现应该通过 Classloader 显式加载.之后,只需应用 Java 安全管理机制来控制对实现类的访问.任何人都可以看到接口,并且对实际实现的访问将仅限于您的 SDK.

The shared classes could be defined by a generally accessible set of interfaces. The actual implementation should be loaded explicitly via a Classloader. After that, simply apply Java Security Management mechanisms to control access to the implementation classes. Anyone can see the interfaces and access to actual implementation will be restricted to your SDK.

(上面的一个变种是每个 web/app 服务器都需要做的.你认为 Tomcat 是如何阻止你访问其他应用程序的公共"类的?)

(A varient of above is what every web/app server needs to do. How do you think Tomcat prevents you from accessing some other app's "public" classes?)

edit:上面的注释是一个运行时机制.还有静态(后)编译方法.例如,APT 在这里可能很有效.自然,我不是在解决您的包的重组(在 OP 中),而只是解决如何保护对一般方法的访问.但这些有点hacky"——类加载的运行时机制是规范的,而且 imo 严格来说更正确.

edit: note above is a runtime mechanism. There are static (post) compile approaches as well. APT for example, could be effective here. Naturally I am not addressing a restructuring of your package (in OP) and only addressing how to secure access to a general approach. But these are a bit 'hacky' -- the runtime mechanism of class loading is canonical and imo strictly more correct.

相关文章