【问题标题】:How to call a method from another class in groovy? [closed]如何在groovy中调用另一个类的方法? [关闭]
【发布时间】:2014-03-17 08:46:00
【问题描述】:

例如,我有一个这样的课程:

class firstOne{

    ....
    def A (){

    }

}

class secondOne{

    // I need to call and use method A from class firstOne
    // even I get error if I try to follow Java like calls
    // firstOne method = new firstOne();
    // method.A()   
}

我已经尝试过http://groovy.codehaus.org/Scripts+and+Classeshttp://groovy.codehaus.org/Groovy+Beans 但没办法。任何类型的建议或示例都会非常有帮助。

【问题讨论】:

  • 这与 grails 有什么关系?此外,最好避免使用大写字母方法
  • 您遇到了什么错误?
  • 你的语句需要在代码块而不是类块中
  • 它在一个 geb 自动化脚本中。它显示一般错误:“org.spockframework.runtime.ConditionNotSatisfiedError”。我将在几分钟内发布有关该错误的更多详细信息。

标签: groovy spock geb


【解决方案1】:

我认为这没有任何问题:

class FirstOne {

    def a() {
        println "a"
    }
}

class SecondOne {

    def b() {
        new FirstOne().a()
        println "b"
    }
}

new FirstOne().a()
println("")
new SecondOne().b()

输出:

a
a
b

【讨论】:

  • 谢谢大佬,帮我解决了问题!
【解决方案2】:

这并不特定于 Groovy/Grails:

firstOne first = new firstOne()
first.A()

此外,您应该将类​​的首字母大写,但方法不应该大写(Java 中的最佳实践)。

【讨论】:

  • 我已经尝试过了,但没有成功!这不是 100% Groovy/Grails,而是完全使用 Java+Groovy!
  • @S.M.AlMamun 那么您的问题中缺少一些部分。我看到你已经发表了关于包含更多细节的评论,所以也许这些会有所帮助。
猜你喜欢
  • 2016-06-14
  • 1970-01-01
  • 2014-03-15
  • 2013-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多