如何从 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?
}
}
我想让我的类 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不管这样做是否“正确”,从 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.
在脚本中间声明一个类并使其依赖于脚本局部变量是糟糕设计的明确标志。如果您无法以面向对象的方式设计整个系统,那么就坚持过程式编程。编写面向对象程序的主要目的是将它们分解为小的独立部分。就您而言,它既不是因式分解,也不是独立的,而且我很确定它没有您可以用语言表达的目的。
换句话说,要么根本不声明
Box
类型,要么像这样使用它:
这样你就可以从
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:And use it like this:
Thus you get it abstracted from
weightArg
andargs[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.