gpt4 book ai didi

java - 如何避免使用内部方法污染 API 类?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:12:43 25 4
gpt4 key购买 nike

背景:

  • 在 C# 中,您可以拥有限定为程序集 (JAR) 的内部方法
  • 内部方法可以被该程序集中的其他类调用,但不能被外部调用。
  • Java 没有任何类似的东西。
  • 创建 API 时,我的内部方法必须公开,以便 API 的其他部分可以调用它们。
  • 这会污染我的 API,并可能允许用户调用内部方法。

TLDR:如果方法是公开的,我如何指示(或更好地保护)我的 API 的内部方法不被 API 类之外的用户调用?

典型例子:

  // public class in com.ashes999.components
class SpriteComponent {
// This method should be internal
public void dispose() { ... }
}

// public class in com.ashes999.management
class SceneManager {
public void changeScene(Scene s) {
for (SpriteComponent s : this.allEntities.allSprites) {
s.dispose();
}
}
}

我只会从 com.ashes999.* 中我自己的类调用 SpriteComponent.dispose。我永远不会期望(甚至希望)其他用户会直接调用它;这样做会导致困惑、破坏、困惑和过早处置未管理的资源,从而导致崩溃。

最佳答案

A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes — you will learn about them in a later lesson.)

At the member level, you can also use the public modifier or no modifier (package-private) just as with top-level classes, and with the same meaning. For members, there are two additional access modifiers: private and protected. The private modifier specifies that the member can only be accessed in its own class. The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

( Access control )

关于java - 如何避免使用内部方法污染 API 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25296777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com