如何从 Groovy 的类中访问声明的脚本字段?

发布于 2024-12-09 21:52:31 字数 365 浏览 0 评论 0原文

假设我有下一个常规代码片段:

def weightArg = args[0]

class Box {

   def width

   def height  

   def double weight() {
       //I want to return the value of weightArg here. How can I do that? 
   }
}

我想让我的类 Box 使用其环境中的一些变量。正确的做法是什么?

看来 weightArg 应该是静态的,我应该能够从 Box 静态初始化程序中获取它,但我无法克服编译器。

Let's say I have the next groovy code snippet:

def weightArg = args[0]

class Box {

   def width

   def height  

   def double weight() {
       //I want to return the value of weightArg here. How can I do that? 
   }
}

I want to let my class Box use some variables from its environment. What's the correct way to do it?

It seems that weightArg should be static and I should be able to get it from Box static initializer, but I cannot manage to overcome the compiler.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

如若梦似彩虹 2024-12-16 21:52:32

不管这样做是否“正确”,从 Box 类中访问权重变量的方法就是简单地删除单词“def”。 此处描述了原因。

Regardless of whether it's "right" to do so or not, the way that you can access your weight variable from within the Box class is to simply remove the word "def". The reason why is described here.

咽泪装欢 2024-12-16 21:52:32

在脚本中间声明一个类并使其依赖于脚本局部变量是糟糕设计的明确标志。如果您无法以面向对象的方式设计整个系统,那么就坚持过程式编程。编写面向对象程序的主要目的是将它们分解为小的独立部分。就您而言,它既不是因式分解,也不是独立的,而且我很确定它没有您可以用语言表达的目的。

换句话说,要么根本不声明 Box 类型,要么像这样

class Box {
  Box(weight) { this.weight = weight }
  def width, height, weight
}

使用它:

def box = new Box(args[0])

这样你就可以从 weightArg 和 < code>args[0] 并且还能够在不同的场景中重用它。

否则,你的程序注定会变得难以管理,从而在第一次修改后就死掉了。面向对象编程存在的几十年里,它已经得到了充分的证明。

另一件需要注意的事情是,当您感觉需要在脚本中引入类时,这是一个可靠的迹象,表明您的程序应该编写为包含包和内容的普通应用程序 - 而不是脚本。

Declaring a class in a middle of a script and making it dependent on scripts local variables is a definite sign of a bad design. If you can't design this whole system in OO way than stick to procedural programming. The main purpose of writing OO programs is factoring them to little independent pieces. In your case it's neither factoring, nor independent, and I'm pretty sure it has no purpose you could express in words.

In other words either don't declare a Box type at all or do it similar to this way:

class Box {
  Box(weight) { this.weight = weight }
  def width, height, weight
}

And use it like this:

def box = new Box(args[0])

Thus you get it abstracted from weightArg and args[0] and also become able to reuse it in different scenarios.

Otherwise you foredoom your program to be unmanageable and therefore dead after first revision. In decades of existence of OO programming it's been pretty much proven.

Another thing to note is that when you get a feeling that you need to introduce classes in your script it is a reliable sign that your program should be written as a normal application with packages and stuff - not as a script.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文