Java是否具有const引用等价物?

这是一段代码:

//Game board is made up of Squares. A player can place GamePieces on a Square. public class CheckersBoard { public boolean PlaceGamePiece(GamePiece gamePiece, int nRow, int nColumn) { return m_theGameBoard[nRow][nColumn].PlaceGamePiece(gamePiece); } private Square[][] m_theGameBoard; } 

假设我正在测试PlaceGamePiece方法(使用junit),我需要访问m_theGameBoard,这样我就可以查看它并validationGamePiece是否放在正确的Square上并且具有正确的数据。

在C ++中,我要么让测试类成为朋友,以便它可以访问私有成员m_theGameBoard,或者我有一个函数返回一个无法修改的const GameBoard(因为它是const):

 const GameBoard& GetGameBoard() const { return m_theGameBoard; } 

现在我可以做任何检查我想在游戏板上做的事情,但我不能修改游戏板,因为它是常量。

Java不支持返回const引用或友元类。 所以我的问题是Java的标准方法是什么? 我是否必须提供一堆get访问器,以便我检查Square上的数据?

更新:我最终写了一个像Kaleb Brasee建议的GetPiece方法。

 public GamePiece GetGamePiece(Point pt) { return new GamePiece(m_theGameBoard[pt.GetRow()][pt.GetColumn()]); } 

请注意,我创建了一个新的GamePiece对象并返回该对象。 我没有返回GameBoards内部参考,因此没有人可以修改游戏板,因为他们只有副本! 太好了! 感谢帮助人员,一些非常好的建议。

仅供参考:当我在这里张贴物品时,我会不断更改物品的名称,对不起,如果这让任何人感到困惑。

将变量定义为protected ,以便如果unit testing位于同一个包中,则可以访问它。

但是,我只是添加一个公共方法getPiece(int row, int col) ,它返回该方块上的片段(如果那里没有片段,则返回null)。 无论如何你可能需要这样的方法,你可以在测试中使用它。

方法或属性的默认访问修饰符是“包受保护的”,这意味着“仅在我的包中可见”。 因此,您可以模拟“友谊”的语义,同时为测试维护单独的代码库,具有两个不同的源文件夹,但具有相同的包结构。

 src |--com | --cchampion | --MyClass.java tests |--com | --cchampion | --TestMyClass.java 

然后,在MyClass.java中

 public class MyClass { private int nonTestedThing; int[][] testedThing; // this is visible to TestMyClass // or // protected int[][] testedThing; // if you want it visible to kids } 

这在任何方面都不理想,但这是一种方法。

是。 您的选择基本上归结为:

 Square getSquareAtLocation(int row, int col) { ... }; 

或者使用其中一个Java集合,然后您可以通过Collections.unmodifiableList(…)

(请注意,如果您使用了多维List,则必须小心包装内部列表以确保它们也不可修改)

如果这只是用于测试,您还可以创建一个返回数组深层副本的函数。