简体   繁体   English

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

[英]How to access declared script fields from within classes in Groovy?

Let's say I have the next groovy code snippet: 假设我有下一个groovy代码片段:

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. 我想让我的班级Box从其环境中使用一些变量。 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. 似乎weightArg应该是静态的,我应该能够从Box静态初始化器中获取它,但我无法克服编译器。

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. 如果你不能以OO方式设计整个系统而不是坚持程序编程。 The main purpose of writing OO programs is factoring them to little independent pieces. 编写OO程序的主要目的是将它们分解为很少的独立部分。 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: 换句话说,要么根本不声明Box类型,要么以这种方式类似:

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. 因此,您可以从weightArgargs[0]抽象出来,并且能够在不同的场景中重用它。

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. 几十年来,OO编程已经证明了这一点。

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. 另外需要注意的是,当您感觉需要在脚本中引入类时,可以确定您的程序应该是作为包含包和内容的普通应用程序编写的 - 而不是脚本。

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". 无论这样做是否“正确”,您可以从Box类中访问权重变量的方法是简单地删除单词“def”。 The reason why is described here . 这里描述原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM