"def" 和 "static def" 在 Gradle 中的区别
Difference between "def" and "static def" in Gradle
如题,defs在Groovy中的这两个到底有什么区别?
可能是文档问题,我找不到任何东西...
没有static
的方法声明将方法标记为实例方法。而带有 static
的声明将使此方法成为静态方法 - 无需创建该 class 的实例即可调用 - 请参阅 https://www.geeksforgeeks.org/static-methods-vs-instance-methods-java/
def
in groovy 将值定义为 duck 类型。值的功能不由其类型决定,它们在运行时进行检查。是否可以在该值上调用方法的问题在运行时得到解答 - 请参阅 optional typing.
static def
意味着该方法将 return 一个鸭子类型的值,并且可以在没有 class.
实例的情况下调用
示例:
假设你有这两个 classes:
class StaticMethodClass {
static def test(def aValue) {
if (aValue) {
return 1
}
return "0"
}
}
class InstanceMethodClass {
def test(def aValue) {
if (aValue) {
return 1
}
return "0"
}
}
您可以调用 StaticMethodClass.test("1")
,但您必须先创建 InstanceMethodClass
的实例,然后才能调用 test
- 例如 new InstanceMethodClass().test(true)
.
如题,defs在Groovy中的这两个到底有什么区别?
可能是文档问题,我找不到任何东西...
没有static
的方法声明将方法标记为实例方法。而带有 static
的声明将使此方法成为静态方法 - 无需创建该 class 的实例即可调用 - 请参阅 https://www.geeksforgeeks.org/static-methods-vs-instance-methods-java/
def
in groovy 将值定义为 duck 类型。值的功能不由其类型决定,它们在运行时进行检查。是否可以在该值上调用方法的问题在运行时得到解答 - 请参阅 optional typing.
static def
意味着该方法将 return 一个鸭子类型的值,并且可以在没有 class.
示例:
假设你有这两个 classes:
class StaticMethodClass {
static def test(def aValue) {
if (aValue) {
return 1
}
return "0"
}
}
class InstanceMethodClass {
def test(def aValue) {
if (aValue) {
return 1
}
return "0"
}
}
您可以调用 StaticMethodClass.test("1")
,但您必须先创建 InstanceMethodClass
的实例,然后才能调用 test
- 例如 new InstanceMethodClass().test(true)
.