Groovy - 方法作用域和可见性
方法作用域和可见性有助于控制其他 class 或外部代码对 class 方法的访问。Groovy 基于 JVM,遵循 Java 的作用域和可见性概念,但有一些细微差别。
可见性修饰符
public − 在 Groovy 中,方法默认是 public,这意味着方法默认可以从其他 class 或脚本访问。
private − 私有访问,表示方法仅在其定义的 class 内可访问。私有方法无法被其他 class 甚至子类访问。
protected − 受保护方法在其声明的 class 及其子类中可访问。同一 package 中的其他 class 也可以访问此类方法。
package-private − 如果方法没有指定任何修饰符,则被视为 package-private,即方法仅在同一 package 内可访问。在 Groovy 中,如果方法没有修饰符,则被视为 public。我们可以使用 @groovy.transform.PackageScope 注解来实现 package-private 作用域。
示例 - 方法作用域和可见性
Example.groovy
package com.
class TestClass {
public void publicMethod() {
println "public method called."
privateMethod()
}
private void privateMethod() {
println "private method called"
}
protected void protectedMethod() {
println "protected method called"
}
void defaultMethod() { // 隐式 public
println "default(Public) method called"
}
}
class TestAnotherClass {
def testInstance = new com..TestClass()
void accessMethods() {
testInstance.publicMethod()
// 由于是 private,此方法无法访问
// testInstance.privateMethod()
// protected 方法可访问,因为 TestAnotherClass 在同一 package 中
testInstance.protectedMethod()
testInstance.defaultMethod()
}
}
def testInstance = new com..TestClass()
testInstance.publicMethod()
testInstance.defaultMethod()
// 无法访问
// testInstance.privateMethod()
// 由于在 package/子类外部,无法访问
// testInstance.protectedMethod()
def testAnotherInstance = new com..TestAnotherClass()
testAnotherInstance.accessMethods()
输出
运行上述程序时,将得到以下结果。
public method called. private method called default(Public) method called public method called. private method called protected method called default(Public) method called
方法内部的作用域
在方法中声明和使用的变量具有局部作用域,这意味着变量仅在方法内部可访问。一旦方法执行完毕,变量作用域也会消失。
main.groovy
class Example {
void testScope() {
def localVariable = "I'm local variable"
println localVariable
}
void anotherMethod() {
// 会导致错误,因为 localVariable 不可用
println localVariable
}
}
def exampleInstance = new Example()
exampleInstance.anotherMethod()
输出
运行上述程序时,将得到以下结果。
Caught: groovy.lang.MissingPropertyException: No such property: localVariable for class: Example groovy.lang.MissingPropertyException: No such property: localVariable for class: Example at Example.anotherMethod(main.groovy:9)