Hi, when I try to set a String value to GlobalVariable I am getting the following error
So I am creating Globalvariable at runtime
String pageNavigatedText =" "
CustomKeywords.'ciautils.ciaUtilities.addGlobalVariable'('pageNavigatedText', pageNavigatedText)
in CustomKeywords
import internal.GlobalVariable as GlobalVariable
static void addGlobalVariable(String name, def value) {
GroovyShell shell1 = new GroovyShell()
MetaClass mc = shell1.evaluate("internal.GlobalVariable").metaClass
String getterName = "get" + name.capitalize()
mc.'static'."$getterName" = { -> return value }
mc.'static'."$name" = value
}
in same CustomKeyword page with in a method I tried to set the value to GlobalVariable and getting the error
GlobalVariable.pageNavigatedText = “test”
//also tried GlobalVariable.pageNavigatedText == “test”, but no error and the variable is still not set the value
And the error I am getting as follows
groovy.lang.ReadOnlyPropertyException: Cannot set readonly property: pageNavigatedText for class: internal.GlobalVariable
String getterName = "get" + name.capitalize()
mc.'static'."$getterName" = { -> return value }
By this code you added a “getter” method to the dynamically-added GlobalVariable.
But you forgot to add a “setter” method.
So the dynamically-added GlobalVariable.pageNavigatedText
does not implement a setter method. Therefore the following statement causes groovy.lang.ReadOnlyPropertyException
GlobalVariable.pageNavigaotrText = "text"
You need to add the “setter” method.
1 Like
@kazurayam, thanks for your reply. I tried as follow and still getting the same error. not sure if the script is correct
static void addGlobalVariable(String name, def value) {
GroovyShell shell1 = new GroovyShell()
MetaClass mc = shell1.evaluate("internal.GlobalVariable").metaClass
String getterName = "get" + name.capitalize()
String setterName = "set" + name.capitalize()
mc.'static'."$getterName" = { -> return value }
mc.'static'."$setterName" = { -> return value }
mc.'static'."$name" = value
}
Thanks
Your current code:
mc.'static'."$setterName" = { -> return value }
Here you created one more “getter” method named “Object setName()”, which is not what you want.
Change this to:
mc.'static'."$setterName" = { newValue -> value = newValue }
This makes “void setName(Object newValue)”. This should be what you want.
1 Like
Thanks so much, it worked now.