Re: How to access global variables from a class?

Per Nyfelt <[email protected]> Mon, 23 Sep 2024 22:17:30 +0200
Newsgroups gmane.comp.lang.groovy.user
Organization Alipsa HB
Message-ID <[email protected]>
You have a scope problem and need to move the logger declaration into 
your A class. Also if slf4j is not available in your classpath, @Grab is 
your friend.

The following works when running the script in the GroovyScriptEngine:

@Grab('org.slf4j:slf4j-simple:2.0.16')
import org.slf4j.LoggerFactory
import org.slf4j.Logger

class A {
   Logger logger = LoggerFactory.getLogger("l")
   public A() {
     logger.info("L")
   }
}
A a = new A()

Note: I don't know how OpenHAB is executing the Groovy code. If it is 
using the GroovyShell then use 
groovy.grape.Grape.grab('org.slf4j:slf4j-simple:2.0.16') instead.See 
https://docs.groovy-lang.org/latest/html/documentation/grape.html for 
details.

Hope this helps.

On 8/21/24 13:16, Дилян Палаузов via users wrote:
> Hello,
>
> OpenHAB 4.2.1 is written in Java and has a Groovy 4.0.11 plugin to programme logic.  It allows writing code outside of classes, which is executed immediately.  When I place a file openhab/jsr223/test.groovy:
>
>
>    import org.slf4j.LoggerFactory
>   
>    logger = LoggerFactory.getLogger("l")
>   
>    class A {
>      public A() {
>        logger.info("L")
>      }
>    }
>    A a = new A()
>
>
> the system logs
>
> 2024-08-21 12:15:21.061 [ERROR] [ipt.internal.ScriptEngineManagerImpl] - Error during evaluation of script ‘/etc/openhab/automation/jsr223/test.groovy’: javax.script.ScriptException: groovy.lang.MissingPropertyException: No such property: logger for class: A
>
> How can I make logger visible within the methods of class A, without passing it as parameter to the constructor?
>
> Also asked athttps://community.openhab.org/t/groovy-how-to-access-global-variable-from-a-class/ .
>
> Kind regards
>    Дилян