【问题标题】:Writing a setter for current path为当前路径编写设置器
【发布时间】:2016-01-03 06:50:40
【问题描述】:

我想为当前路径编写 getter 和 setter。

private Path currentPath;
public Path getCurrentPath() {
    currentPath = Paths.get(".").toAbsolutePath().normalize();
    return currentPath;
}

@Override
public void setCurrentPath(Path p) {
     currentPath = Paths.get(".").toAbsolutePath().normalize();
}

看起来 getter 工作正常,但 setter 不行。 有人可以帮我吗?

【问题讨论】:

  • 因为您没有使用p 类型的参数path
  • 只做p.toAbsolutePath().normalize();
  • 另外,你必须确保一旦你的 setter 设置了currentPath,你的类会为你提供获取它的方法。现在,您的 getter 将丢弃 currentPath 中的所有内容并将其设置为其他内容。所以这会让你的 setter 没用,除非你的类中有其他方法使用currentPath

标签: java path


【解决方案1】:

您没有使用传递给您的 setter 方法的参数 p。要使用它,您需要执行以下操作:

@Override
public void setCurrentPath(Path p) {
     currentPath = p.toAbsolutePath().normalize();
}

getter 也不应该改变 currentPath 的值(即它应该返回 currentPath 的任何值)

【讨论】:

  • 这个吸气剂好吗? return Paths.get(".").toAbsolutePath().normalize();
  • 没有。您的 getter 应该是幂等的,即不应对您的 currentPath 造成任何副作用。所以应该像public Path getCurrentPath() {return currentPath;}这样简单
  • 你能告诉我如何解决问题 - getter 总是返回相同的
  • 是的,就像我说的那样。除非您使用 setter 方法重置值,否则您将获得相同的值,这就是它应该的样子。
  • 我们可以聊天吗?
猜你喜欢
  • 1970-01-01
  • 2014-01-30
  • 2018-04-19
  • 2015-08-08
  • 2012-08-29
  • 1970-01-01
  • 2023-04-03
  • 2017-09-19
  • 2017-06-18
相关资源
最近更新 更多