問題
爲什麼靜態屬性PATH2
不是其他靜態屬性PATH1
後,被分配一個新的價值變化?
請參閱下面的示例中的assert
。
例
println "--- Original values ---"
println "Configuration.PATH1: ${Configuration.PATH1}"
println "Configuration.PATH2: ${Configuration.PATH2}"
println ""
println "--- Values after changing PATH1---"
Configuration.PATH1 = "c:\\test"
println "Configuration.PATH1: ${Configuration.PATH1}"
println "Configuration.PATH2: ${Configuration.PATH2}"
println ""
assert Configuration.PATH2 == "c:\\test\\subfolder"
class Configuration {
static public String PATH1 = "c:\\production"
static public String PATH2 = "${PATH1}\\subfolder"
}
輸出
--- Original values ---
Configuration.PATH1: c:\production
Configuration.PATH2: c:\production\subfolder
--- Values after changing PATH1 ---
Configuration.PATH1: c:\test
Configuration.PATH2: c:\production\subfolder // <-- Hasn't changed
Assertion failed:
assert Configuration.PATH2 == "c:\\test\\subfolder"
| |
| false
c:\production\subfolder
假設
似乎PATH2
在一開始就只設置一次上課時第一次訪問。
我想這是正確的行爲。誰能證實這個假設?
另外:你能告訴我一個代碼示例它是如何正確完成的嗎?這是應該如何正確完成的:通過實施getPATH2()
方法?
class Configuration {
static public String PATH1 = "c:\\production"
static public String PATH2 = "${PATH1}\\subfolder"
static public getPATH2() {
return "${PATH1}\\subfolder"
}
}
它是正確的,因爲類Configuration
實例化後,這是什麼樣子的記憶是什麼?
class Configuration {
static public String PATH1 = "c:\\production"
static public String PATH2 = "c:\\production\\subfolder" // Variable PATH1 has been resolved after class instantiation and is sort of "gone" so changing PATH1 has no effect on PATH2 anymore?
static public getPATH2() {
return "${PATH1}\\subfolder"
}
}
它是正確的,因爲變量PATH1
佔位符的PATH2
分配已經解決,是一種「水漲船高」,從而改變PATH1
對PATH2
沒有效果了嗎?
問題總結
- 是假設是否正確?
- 實現它的正確方法是什麼?
請問你說的「新計算每次你問它的價值,」只有屬於帶有'getPATH2()'的第一個代碼示例,而不是'GString PATH2'的第二個代碼示例?當我拿出我的代碼示例,並且只將'String PATH2'改爲'GString PATH2'時,控制檯輸出保持不變,即每次詢問其值時都不會重新評估'GString PATH2'。正確? – Lernkurve